gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:39 24 4
gpt4 key购买 nike

我喜欢在我的 Linux Mint 系统上从 Python 运行一个 shell 命令。具体来说,该命令运行所有 Bleachbit 清洁器并完美运行手动运行时很好。

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

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

我在执行 python 命令时也关闭了 firefox/浏览器。

有人对如何解决这个问题有什么建议吗?

我的代码:

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

最佳答案

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)

关于Python - 执行 shell 命令在 Linux 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com