运行从文件读取输入并打印到另一个文件的可执行文件

时间:2017-03-23 00:12:24

标签: python

我正在尝试从Python程序中运行一个文件map.py.我的代码如下:

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)

运行此代码后,出现以下错误:

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:

这是map.py将要做的一个虚拟示例:

print("hi")

虽然应该有一些标准的东西。该计划似乎并不适合我,我不知道为什么。我已经盯着这几个小时,我真的很感激你的帮助!

2 个答案:

答案 0 :(得分:0)

如果要在当前的python shell中运行该代码,则应创建父文件夹模块并导入该文件并直接访问它。

如果您想在单独的流程中运行该文件并使用subprocess.check_output

获取结果

答案 1 :(得分:0)

如果要从一个文件中读取并将其写入另一个文件。你可以做这样的事情

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()

我认为这对你想要做的事情有用。

相关问题