Python send data to an executable passed as parameter in terminal

时光总嘲笑我的痴心妄想 提交于 2019-12-14 03:18:04

问题


I have a python script which gets 2 parameters from the command line, an executable and a file. After I do some computation I need to pass by stdin the result of this computation to the executable.

1) is this even possible? 2) if so, how can I do this in Python


回答1:


First, you should never use os.system that's a very dangerous and bad habit.

As for your problem, using subprocess you can do the following:

from subprocess import Popen, PIPE, STDOUT

#do some stuff 
data = do_some_computation_from_file

#prepare your executable using subprocess.Popen
exe = Popen(['your_executable'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

#pass in the computed data to the executable and grap the result
result = exe.communicate(input=data)[0]


来源:https://stackoverflow.com/questions/15775772/python-send-data-to-an-executable-passed-as-parameter-in-terminal

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