在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
时,要特别小心,因为它可能会导致安全漏洞。确保你只运行可信的命令和脚本。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:python如何执行bash命令