Python OS.System或子过程呼叫命令行自动化
我希望能够调用一些执行参数的可执行文件,然后将输出转换为文件。我试图同时使用OS.System和子过程呼叫,但无济于事。这是我希望python为我执行的内容的示例...
c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt
注意到绝对路径,因为我将穿越数百个各种目录以在文件上采取行动等。
非常感谢!
我尝试过的一些示例:
subprocess.run(['c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt']
subprocess.call(r'"c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt"']
subprocess.call(r'"c:\directory\executable_program.exe" -f "w:\directory\input_file.txt > Z\directory\output_file.txt"']
I would like to be able to call some executables that take in parameters and then dump the output to a file. I've attempted to use both os.system and subprocess calls to no avail. Here is a sample of what I'd like python to execute for me...
c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt
Notice the absolute paths as I will be traversing hundreds of various directories to act on files etc..
Many thanks ahead of time!
Some examples that I've tried:
subprocess.run(['c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt']
subprocess.call(r'"c:\directory\executable_program.exe -f w:\directory\input_file.txt > Z\directory\output_file.txt"']
subprocess.call(r'"c:\directory\executable_program.exe" -f "w:\directory\input_file.txt > Z\directory\output_file.txt"']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的尝试包含各种引用错误。
应该有效,
r
前缀在子过程运行之前在Python上保护和删除背面闪烁,而缺乏[...]
围绕该值将其传递给它。逐字化到外壳(因此,shell = true
)。在Windows上,即使它不是列表,您也可以将命令放在方括号中,并且在某些情况下省略
shell = true
。如果您想避免使用壳,请尝试
说明如何将方括号中的字符串中的字符串列表作为第一个参数作为
subprocess.run
的第一个参数。Your attempts contain various amounts of quoting errors.
should work, where the
r
prefix protects the backslashes from being interpreted and removed by Python before the subprocess runs, and the absence of[...]
around the value passes it verbatim to the shell (hence,shell=True
).On Windows you could get away with putting the command in square brackets even though it's not a list, and omitting
shell=True
in some circumstances.If you wanted to avoid the shell, try
which also illustrates how to properly pass a list of strings in square brackets as the first argument to
subprocess.run
.