温馨提示×

python如何运行bash命令

小亿
93
2024-12-05 09:50:28
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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!'。我们将stdoutstderrtext参数设置为subprocess.PIPE,以便捕获命令的输出。shell=True表示我们在一个shell环境中运行这个命令。

注意:在使用shell=True时,要特别小心,因为它可能会导致安全漏洞。确保你只运行可信的命令和脚本。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python如何执行bash命令

0