简体   繁体   English

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

[英]Python - Executing shell command does not work on Linux

I like to run a shell command from Python on my Linux Mint system. 我喜欢在Linux Mint系统上从Python运行shell命令。 Specifically the command runs all Bleachbit cleaners and works perfectly fine when run maually. 具体来说,该命令可运行所有Bleachbit清理程序,并且在手动运行时运行良好。

Yet, trying to run the same command via the subprocess.call module always results in an exception raised. 但是,尝试通过subprocess.call模块运行同一命令总是会引发异常。

I just can not see why it should not work. 我只是不明白为什么它不起作用。 The command does not require sudo rights, so not requiring right not given. 该命令不需要sudo权限,因此不需要不需要的权限。

I also have firefox/browsers closed when executing the python command. 执行python命令时,我也关闭了firefox / browsers。

Anybody, any suggestions how to fix this issue? 有人,对解决这个问题有什么建议吗?

My code: 我的代码:

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

When shell is False you need to pass a list of args: 当shell为False时,您需要传递一个args列表:

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

subprocess module does not run the shell by default therefore the shell wildcards (globbing patterns) such as * are not expanded. subprocess模块默认情况下不会运行外壳程序,因此外壳程序通配符(globbing模式)(例如*不会展开。 You could use glob to expand it manually: 您可以使用glob手动将其扩展:

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

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

If the command is more complex and you have full control about its content then you could use shell=True to run it in the shell: 如果命令更复杂,并且可以完全控制其内容,则可以使用shell=True在shell中运行它:

subprocess.check_call("bleachbit -c firefox.*", shell=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM