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

python 旧版本中(2.4以前)调用shell脚本方法:
os.popen(command[, mode[, bufsize]])
os.system(command)
commands.getstatusoutput()
1,os.system(command)调用系统命令,完成后退出,返回结果是命令执行状态,一般是0
               返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码。
>>os.system('pwd')
>>./opt/code
>>os.system('cd hello')
>>0
>>os.system('pwd')
>>./opt/code
- 父进程的环境变量(environment variables)会默认传递到子进程中(工作目录PWD就是环境变量之一)
- 使用system函数,子进程无法影响父进程中的环境变量
其实简单点说,就是os.system()的每一次操作都是开启一个子进程,操作完成后,会返回父进程,但是无法改变父进程的环境变量。
2,os.popen(command):这种调用方式是通过管道的方式来实现,函数返回一个file对象,可以对这个文件对象进行相关的操作。
>> 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' at 0x7f6cbbbee540>
>>> f.readlines()
['hello python!\n', 'hello world!\n']
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')

猜你喜欢

转载自blog.csdn.net/u010622613/article/details/80053429
今日推荐