2015-11-10 51 views
0
output = cStringIO.StringIO() 
output.write('string') # this emulates some_file.txt 

p = subprocess.Popen(['perl', 'file.pl'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
line, _ = p.communicate(output.getvalue()) 
print line 
output.close() 

这打印Can't open perl script "file.pl": No such file or directory。 python脚本和perl文件在同一个目录下!获取`perl file.pl <some_file.txt` shell命令的输出

我想line是的perl file.pl < some_file.txt

输出如何做到这一点?

+0

是在当前工作目录中的file.pl? –

+0

@ ChadS.Yes,它在同一个目录中。我已经更新了这个问题。 –

+0

你的问题似乎与'subprocess'和'cStringIO'没有任何关系。尝试指定'file.pl'的绝对路径。 – martineau

回答

0

我想行是perl file.pl < some_file.txt

#!/usr/bin/env python 
from subprocess import check_output 

with open('some_file.txt', 'rb', 0) as file: 
    line = check_output(['perl', 'file.pl'], stdin=file) 

输出就可以了Can't open perl script "file.pl": No such file or directory,通过完整路径file.pl例如,如果是在同一个目录中的Python脚本,那么你可以使用get_script_dir() function来获取路径。