python: os.system() and os.popen()

In the old version of python (before 2.4), the shell script method is called:
os.popen(command[, mode[, bufsize]])
os.system(command)
commands.getstatusoutput()
1, os.system(command) calls the system command, Exit after completion, the return result is the command execution status, generally 0
               returns a 16-bit binary number, the low bit is the signal number that kills the called script, and the high bit is the exit status code of the script.
>>os.system('pwd')
>>./opt/code
>>os.system('cd hello')
>>0
>>os.system('pwd')
>>./opt/code
- parent The environment variables of the process will be passed to the child process by default (the working directory PWD is one of the environment variables)
- using the system function, the child process cannot affect the environment variables in the parent process.
In fact, simply put, it is os.system( ) each operation is to open a child process. After the operation is completed, it will return to the parent process, but the environment variables of the parent process cannot be changed.
2, os.popen(command): This calling method is implemented through a pipeline, and the function returns a file object, which can perform related operations on this file object.
>> import os
>>> os.popen("./a.sh")
<open file './a.sh', mode 'r' at 0x7f6cbbbee4b0>
>>> f=os.popen("./a .sh")
>>> f
<open file './a.sh', mode 'r'


3,commands.getstatusoutput(): 可以读取程序执行的返回值
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326702861&siteId=291194637