在Python中,你可以使用subprocess模块来运行bash命令
import subprocess
# 运行一个简单的bash命令
command = "echo 'Hello, World!'"
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
print("命令输出:", result.stdout)
print("错误输出:", result.stderr)
print("返回码:", result.returncode)
在这个例子中,我们使用subprocess.run()函数来运行一个简单的bash命令echo 'Hello, World!'。我们将stdout、stderr和text参数设置为subprocess.PIPE,以便捕获命令的输出。shell=True表示我们在一个shell环境中运行这个命令。
注意:在使用shell=True时,要特别小心,因为它可能会导致安全漏洞。确保你只运行可信的命令和脚本。