使两个脚本进行通信 [英] Making two scripts communicate

查看:132
本文介绍了使两个脚本进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使两个程序(例如脚本A(。py)和脚本B(。exe))进行通信。
这两个程序都处于无限循环中:脚本A需要写入脚本B的标准输入,然后读取脚本B的标准输出,然后再次写入,等等。脚本BI无法更改。



两个文件都在我的硬盘上,因此与网络相比,我必须有一种更好的解决方法。但是,我可以使用脚本A编写文件。
这不是课程作业,我正在为游戏编写GUI,并且已经对AI进行了一些预编程。
我曾经考虑过使用管道(python scripta.py | scriptb.exe),但这似乎需要脚本A才能完成脚本B的执行。再说一次,因为我从未使用过管道,所以我可能会错过一些显而易见的东西。



我希望如果所需的工具是标准库的一部分,但如果它们

该解决方案必须同时在Linux和Windows上运行。
你们中有人能指出我正确的方向吗?
谢谢您的时间。

解决方案

如果您使用脚本A中的脚本B启动子进程模块,您将能够直接与其stdin和stdout进行交互。例如:

 从子流程导入Popen,PIPE 

prog = Popen( scriptA.exe ,shell = True,stdin = PIPE,stdout = PIPE)

prog.stdin.write(这将转到脚本A\n)
print prog.stdout.read( )

prog.wait()#等待脚本A完成

请注意,因为调用read会阻塞,这意味着如果脚本没有要打印的内容,则调用将挂起,直到执行该操作为止。避免这种情况的最简单方法是使用线程。


I have to make two programs (for example a "script A" (.py) and "script B"(.exe)) communicate. Both programs are on a infinite loop: Script A needs to write to the stdin of script B and afterwards read the stdout of script B thereafter write again etc. Script B I cannot change.

Both files are on my hard disk, so I there must be a better way to solve this than networking. I can, however, write files with script A. This is not course homework, I am writing a GUI for a game and I have a few AI's preprogrammed. I have thought of piping (python scripta.py | scriptb.exe), but that seemed to require script A to finish before script B could execute. Then again, as I've never used piping, I might have missed something obvious.

I would prefer if the tools needed would be part of standard library, but if they're not, too bad.

The solution would have to work on both Linux and Windows. Could any of you point me in the right direction? Thank you for your time.

解决方案

If you start "Script B" from within "script A" using the subprocess module, you will be able to directly interact with its stdin and stdout. For example:

from subprocess import Popen, PIPE

prog = Popen("scriptA.exe", shell=True, stdin=PIPE, stdout=PIPE)

prog.stdin.write("This will go to script A\n")
print prog.stdout.read()

prog.wait() # Wait for scriptA to finish

Just be careful, as calls to read will block, meaning if the script doesn't have anything to print, the call will hang until it does. The easiest way to avoid this is to use threading.

这篇关于使两个脚本进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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