Python - 执行shell命令在Linux上不起作用

时间:2014-10-13 20:22:31

标签: python linux shell subprocess

我喜欢在我的Linux Mint系统上运行Python命令。 具体来说,该命令运行所有Bleachbit清洁工并完美运行 当你实际运行时很好。

然而,尝试通过subprocess.call模块运行相同的命令 总是会引发异常。

我只是看不出它为什么不起作用。 该命令不需要sudo权限,因此不需要 没有给出权利。

执行python命令时,我也关闭了firefox / browsers。

任何人,有任何建议如何解决这个问题?

我的代码:

try:
    subprocess.call('bleachbit -c firefox.*') 
except:
    print "Error."

2 个答案:

答案 0 :(得分:0)

当shell为False时,您需要传递一个args列表:

import subprocess
try:
    subprocess.call(["bleachbit", "-c","firefox.*"])
except:
    print ("Error.")

答案 1 :(得分:0)

默认情况下,

subprocess module不运行shell,因此不会扩展*等shell通配符(通配模式)。您可以使用glob手动展开它:

#!/usr/bin/env python
import glob
import subprocess

pattern  = 'firefox.*'
files = glob.glob(pattern) or [pattern]
subprocess.check_call(["bleachbit", "-c"] + files)

如果命令更复杂并且您可以完全控制其内容,那么您可以使用shell=True在shell中运行它:

subprocess.check_call("bleachbit -c firefox.*", shell=True)
相关问题