Linux command to invoke Python and get the return value

A method of using the system os module methods : os.system (cmd), the return value is returned after the shell instruction execution status code , int type, shell 0 indicates successful execution of the instruction, 256/512 represents not found, the method is applicable shell command output does not need to scene content .

os.system (cmd) will start sub-process, execute cmd in the child, if cmd with operational content, will be displayed on the standard output.

for example:

1. list all files in the current directory.

import os
Val = the os.system ( ' LS -Al ' )
 Print Val # output is 0 
Val = the os.system ( ' LS -Al non_exist_folder ' )
 Print Val # output 512 
Val = the os.system ( ' LS -Al | grep non_exist_val ' )
 Print Val # output 256

The second method used os.popen, () , which returns the result of the instruction execution shell in the form of files , use read () or the readlines () method needs to fetch the content.

os.system (cmd) or os.popen (cmd), the former exit status return value is a script, which is the output of the return value of the content of the script execution process. Depending on demand and select the actual use.

For Li:

import os
os.popen ( ' ls -l ' )
Output: <File Open ' LS -l ' , MODE ' R & lt ' AT 0x7f46af044930> 
os.popen, ( ' LS -l ' ) .read () # Returns a string type of result 
output: ' Total 0 \-n-RW-RW On Dec. 1 roaddb roaddb 0 -r--. 11 10:09 a.txt \-n-RW RW-r---0. 1 roaddb roaddb On Dec. 11 10:09 b.txt \ n- ' 
os.popen, ( ' LS -l ' ) .readlines () # returns a list of the type of result 
output: [ ' Total 0 \ n- ' , ' -rw-r---RW. 1 roaddb roaddb On Dec. 11 0 10:09 a.txt \ n- ' , '-rw-rw-r-- 1 roaddb roaddb 0 Dec 11 10:09 b.txt\n']

val=os.popen('ls -al')
for i in val.readlines():
    print i  

Three methods used commands module , there are three methods can be used:

(1) commands.getstatusoutput (cmd), which is a return command in the form of a tuple (status, output) return status and the execution result of the execution. Wherein cmd is actually performed according to {cmd;} Embodiment 2> & 1, the output contains information or console output error, output line breaks not included in the tail.

(2) commands.getoutput (cmd), returns the output of cmd.

(3) commands.getstatus (file), returns ls -l file execution result string , called getoutput, this method is not recommended

import commands
aa=commands.getstatusoutput('ls -l')
Output: (0, ' Total 0 \-n-RW RW-r---0. 1 roaddb roaddb On Dec. 11 10:09 a.txt \-n-RW RW-r---0. 1 roaddb roaddb On Dec. 11 10:09 B .txt ' ) 
 # returns a tuple Comparative os.popen (cmd) returns the result, we found that output does not contain newline trailing 
BB = commands.getoutput ( ' LS -l ' )   # returns only the execution result 
output: ' 0 Total \-n-RW RW-r---0. 1 roaddb roaddb On Dec. 11 10:09 a.txt \-n-RW RW-r---0. 1 roaddb roaddb On Dec. 11 10:09 b.txt ' 
 CC = Commands .getstatus ( ' a.txt ' )   # query the status of a file 
output: ' -rw-r-- RW-0. 1 roaddb roaddb 10:09 a.txt On Dec. 11 ' 
dd = commands.getstatusoutput (' LS non_exist_folder the -l ' )   # execution result includes the console output or error message 
output: (512, " LS: CAN not Access 'non_exist_folder': No SUCH File or Directory " )

os.popen (cmd) returns a file-like object, commands.getoutput (cmd) Returns a string type output, more convenient to use them in many cases more.

Method IV, subprocess module allows you to create many sub-processes, can be specified when creating the child process and the child process input and output, error output pipeline, after performing can get output and execution status.

(1) subprocess.run (): python3.5 a new function, executes the specified command, wait command returns an instance of a class containing CompletedProcess after completion of execution of the execution result.

(2) subprocess.call (): the specified order, the state returns to the command execution, the function is similar to the os.system (cmd) .

(3) subprocess.check_call (): python2.5 a new function, the specified order, if you perform a successful status code is returned, otherwise an exception is thrown.

说明:subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)

     subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

     subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

    args: represents a shell command, if the given string shell command, such as "ls -l" it is necessary that the shell = Ture. Otherwise the default representation shell variables, such as "ls", in an array "- l".

    When using more complex shell statement, the module can first use shlex shlex.split () method to help formatting commands, and then passed to the run () method or Popen.

subprocess.run (), subprocess.call (), subprocess.check_call (), subprocess.check_output () function are advanced through the package of subprocess.Popen to achieve, so if we need more complex functions, you can subprocess .Popen to complete

For use chestnut:

import shlex
import subprocess
command='ls -l'
args=shlex.split('ls -l')
BB = subprocess.Popen (args) # BB Popen is an object, the object can not be read () or the readlines () to read 
Output: Total 0
 -rw-r---RW. 1 roaddb roaddb On Dec. 11 0 10: 09 a.txt
 -rw-rw-r-- 1 roaddb roaddb 0 Dec 11 10:09 b.txt # where need to click on a line break will end 
AA = subprocess.call ( ' LS the -l ' , shell = True )   # whose return value shell command execution return code 
output: Total 0
 -rw-r---RW. 1 roaddb roaddb On Dec. 11 0 10:09 a.txt
 -rw-r---RW On Dec. 11 0. 1 roaddb roaddb 10:09 b.txt # direct return

 Follow-up also need to continue to learn: https://www.cnblogs.com/lincappu/p/8270709.html

In the case of Python3

Expectations: curl command you want to execute in Python3 and returns the results, the results returned when json body

analysis:

cmd='curl -s "http://127.0.0.1:8080/xxxxx"' 

1) Use os.system (cmd) output can not get content

2) Use os.popen (cmd) .read () can be acquired json body return $ {aa}, by json.loads $ {aa}) may be converted to the dictionary json body style (

3) commands modules are discarded Python3.0

4) (cmd) output subprocess.getstatusoutput similar python2 in commands.getstatusoutput (cmd), returns a tuple, the second value tuple execution result $ {aa}, by json.loads ($ {aa }) json body can be converted to the dictionary style.

Reference: https://www.cnblogs.com/pengpp/p/9833349.html

Guess you like

Origin www.cnblogs.com/mianbaoshu/p/12024498.html