Run Perl code (with output to file) from Python

ⅰ亾dé卋堺 提交于 2019-11-30 20:49:51

问题


I'm trying to run a Perl script from Python. I know that if run the Perl script in terminal and I want the output of the Perl script to be written a file I need to add > results.txt after perl myCode.pl. This works fine in the terminal, but when I try to do this in Python it doesn't work.

This the code:

import shlex
import subprocess

args_str = "perl myCode.pl > results.txt"
args = shlex.split(args_str)
subprocess.call(args)

Despite the > results.txt it does not output to that file but it does output to the command line.


回答1:


subprocess.call("perl myCode.pl >results.txt", shell=True)

or

subprocess.call(["sh", "-c", "perl myCode.pl >results.txt"])

or

with open('results.txt', 'wb', 0) as file:
    subprocess.call(["perl", "myCode.pl"], stdout=file)

The first two invoke a shell to execute the shell command perl myCode.pl > results.txt. The last one executes perl directly by having call do the redirection itself. This is the more reliable solution.



来源:https://stackoverflow.com/questions/29264377/run-perl-code-with-output-to-file-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!