python执行bash脚本
时间: 2025-01-16 16:09:30 浏览: 28
如何在 Python 中调用和执行 Bash 脚本
使用 subprocess
模块调用 Bash 脚本
Python 的 subprocess
模块允许程序生成新的进程,连接到它们的输入/输出/错误管道,并获取返回码。这对于需要与操作系统交互的任务非常有用。
可以使用 subprocess.run()
函数来执行 bash 命令或脚本并等待其完成。下面展示了一个例子:
import subprocess
result = subprocess.run(['./test.sh', 'parameter'], capture_output=True, text=True)
print(result.stdout)
这段代码会运行名为 test.sh
的 shell 脚本并向它传递一个参数字符串 'parameter'
[^1]。
如果希望更灵活地处理子进程的标准输入、标准输出以及标准错误流,则可以选择使用 Popen
类:
with subprocess.Popen(
['./test.sh', 'param'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) as process:
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
exit_code = process.returncode
print(f'Bash script exited with code {exit_code}')
此段代码逐行读取来自 bash 脚本的标准输出直到结束,并打印每一行的内容;最后还报告了退出状态码。
对于简单的命令可以直接利用 check_output
方法获得结果而无需关心其他细节:
output = subprocess.check_output('./test.sh param').decode('utf-8')
print(output)
这里假设 test.sh
是可执行文件并且位于当前工作目录下。注意要确保给定路径正确无误[^4]。
相关推荐


















