Python将数据发送到在终端中作为参数传递的可执行文件 [英] Python send data to an executable passed as parameter in terminal

查看:847
本文介绍了Python将数据发送到在终端中作为参数传递的可执行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本从命令行获取2个参数,一个可执行文件和一个文件。在我做一些计算后,我需要通过stdin这个计算的结果到可执行文件。

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)这是甚至可能吗?
2)如果是这样,我怎么在Python中这样做

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

推荐答案

首先,你不应该使用os.system这是一个非常危险和坏的习惯。

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]

这篇关于Python将数据发送到在终端中作为参数传递的可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆