如何在Python中不使用shell=True执行带输出重定向的系统命令?
不使用shell=True实现命令重定向
你之前的写法错误在于:当shell=False(默认值)时,subprocess会将列表中的每个元素直接作为目标程序的命令行参数。>是Shell的重定向语法,并非program的参数,所以你把>和test.out传给program后,它会将这些当成要读取的文件名,导致报错。
下面是两种安全的实现方式:
方法1:通过Python文件句柄重定向输出
直接在Python中打开输出文件,将文件对象传递给subprocess的stdout参数,实现输出重定向:
import subprocess # 用上下文管理器打开文件,自动处理资源释放 with open('test.out', 'w') as out_file: # 执行program,传入参数test.in,将标准输出定向到out_file subprocess.run(['program', 'test.in'], stdout=out_file)
如果需要确保命令执行成功(非零退出码时抛出异常),可以添加check=True参数:
import subprocess with open('test.out', 'w') as out_file: subprocess.run(['program', 'test.in'], stdout=out_file, check=True)
方法2:直接指定输出文件(Python 3.7+)
Python 3.7及以上版本支持直接将文件对象传入stdout,写法更简洁(仍推荐用上下文管理器避免资源泄漏):
import subprocess subprocess.run(['program', 'test.in'], stdout=open('test.out', 'w'))
补充场景
如果你的program不是通过命令行参数读取test.in,而是从标准输入读取内容,那么还需要传递输入文件句柄:
import subprocess with open('test.in', 'r') as in_file, open('test.out', 'w') as out_file: subprocess.run(['program'], stdin=in_file, stdout=out_file, check=True)
内容的提问来源于stack exchange,提问作者Imahn
相关产品推荐
相关产品推荐

