in *_*eps 2 python windows shell
在我的python脚本中,我试图运行一个打印输出的Windows程序.但我想将该输出重定向到文本文件.我试过了
command = 'program' + arg1 + ' > temp.txt'
subprocess.call(command)
Run Code Online (Sandbox Code Playgroud)
程序是我的程序名称,arg1是参数.但它不会将输出重定向到文本文件它只是在屏幕上打印.
任何人都可以帮我怎么做?谢谢!
将文件对象传递给stdout参数subprocess.call():
with open('myoutfilename', 'w') as myoutfile:
subprocess.call(cmd, stdout=myoutfile)
Run Code Online (Sandbox Code Playgroud)
您可以使用shell=True在subprocess.call
但是,(更好)这样做的方法是:
command = ['program',arg1]
with open('temp.txt','w') as fout:
subprocess.call(command,stdout=fout)
Run Code Online (Sandbox Code Playgroud)
这样可以将shell从整个系统中移除,使其更加独立于系统,并且它还可以使您的程序免受"shell注入"攻击(考虑arg1='argument; rm -rf ~'或等效于Windows).
上下文管理器(with语句)是一个好主意,因为它可以保证在离开"上下文"时正确刷新和关闭文件对象.
请注意,如果你不使用是很重要shell=True的subprocess.Popen(或类似)类,你应该通过参数作为一个列表,而不是一个字符串.您的代码将以这种方式更加强大.如果你想使用一个字符串,python提供了一个方便的功能,shlex.split可以像你的shell一样将字符串拆分成参数.例如:
import subprocess
import shlex
with open('temp.txt','w') as fout:
cmd = shlex.split('command argument1 argument2 "quoted argument3"'
#cmd = ['command', 'argument1', 'argument2', 'quoted argument3']
subprocess.call(cmd,stdout=fout)
Run Code Online (Sandbox Code Playgroud)