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

本文介绍了Python旧版本中调用Shell脚本的三种方法:os.system(), os.popen()及commands.getstatusoutput()。详细解释了每种方法的特点、使用场景及返回值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值