从Python运行Perl代码(输出到文件)



我正在尝试从Python运行Perl脚本。我知道,如果在终端中运行Perl脚本,并且我希望Perl脚本的输出被编写为一个文件,我需要在perl myCode.pl之后添加> results.txt。这在终端中很好,但当我尝试在Python中这样做时,它不起作用。

这是代码:

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

尽管有> results.txt,但它不会输出到该文件,而是输出到命令行。

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

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

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

前两个调用shell来执行shell命令perl myCode.pl > results.txt。最后一个直接执行perl,由call自己执行重定向。这是更可靠的解决方案。

最新更新