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

查看:20
本文介绍了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天全站免登陆