[英]Running an executable that reads input from a file and prints to another file
I am trying to run a file, map.py, from within a Python program. 我正在尝试从Python程序中运行map.py文件。 My code is as follows: 我的代码如下:
import sh
exe = sh.Command("./path/to/map.py")
file_in = open("./path/to/inputfile") #inputfile has no extension
out_file = "./path/to/outputfile" #outputfile has no extension
exe(_in=file_in, _out=out_file)
After running this code, I get the following error: 运行此代码后,出现以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/vagrant/venv/lib/python3.5/site-packages/sh.py", line 1427, in __call__
return RunningCommand(cmd, call_args, stdin, stdout, stderr)
File "/vagrant/venv/lib/python3.5/site-packages/sh.py", line 774, in __init__
self.wait()
File "/vagrant/venv/lib/python3.5/site-packages/sh.py", line 792, in wait
self.handle_command_exit_code(exit_code)
File "/vagrant/venv/lib/python3.5/site-packages/sh.py", line 815, in handle_command_exit_code
raise exc
sh.ErrorReturnCode_255:
RAN: /vagrant/exec/word_count/map.py
STDOUT:
STDERR:
Here is a dummy example of what map.py would be doing: 这是map.py将要执行的虚拟示例:
print("hi")
There should be some stdout stuff though. 不过应该有一些标准输出的东西。 The program just doesn't seem to be running for me and I'm not sure why. 该程序似乎并没有为我运行,我不确定为什么。 I've been staring at this for hours, I would really appreciate the help! 我已经盯着看了好几个小时,非常感谢您的帮助!
If you want to run that code in your current python shell, you should make the parent folder modules and import that file and access it directly. 如果要在当前的python shell中运行该代码,则应制作父文件夹模块并导入该文件并直接访问它。
If you want to run the file in a separate process and get the results use subprocess.check_output 如果要在单独的进程中运行文件并获取结果,请使用subprocess.check_output
If you want to read from one file and write it to another. 如果要从一个文件读取并将其写入另一个文件。 You could do something like this 你可以做这样的事情
input_f = open(input, 'r')
output_f = open('workfile', 'w')
lines = input_f.readlines()
for i in lines:
#replicates whatever map.py does
output_f.write(new_line)
output_f.flush()
I think that will work for what you are trying to do. 我认为这将适合您的尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.