subprocess 模块
@(python3)
subprocess.call 和 subprocess.check_call
执行命令,返回状态码。
两者唯一的区别在于返回值。执行成功,都返回 0;执行失败,check_call 将raise出来一个CalledProcessError。
import subprocess
subprocess.call(['ls', '-l'])
subprocess.call(['ls -l'], shell=True)
注意shell=True
的用法,支持命令以字符串的形式传入。
subprocess.getoutput(cmd)
以字符串的形式返回执行结果,错误或者正确都会返回,命令本身不会报错
import subprocess
a = subprocess.getoutput('ls /Users/wangxiansheng/desktops')
print(a)
print(type(a))
ls: /Users/wangxiansheng/desktops: No such file or directory
<class 'str'>
变量 a 保存了错误信息
并返回。
subprocess.getstatusoutput(cmd)
返回包含执行结果状态码和输出信息的元组。
import subprocess
a = subprocess.getstatusoutput('ls /Users/wangxiansheng/desktops')
print(a)
print(type(a))
(1, 'ls: /Users/wangxiansheng/desktops: No such file or directory')
<class 'tuple'>