栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

发送到python3程序的stdin

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

发送到python3程序的stdin

你所需要的是一些符合

主.py
):

from subprocess import Popen, PIPE, STDOUTx = Popen(['some_child.exe', 'parameter'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)while x.poll() is None:    child_output = x.stdout.readline()    print(child_output)    if b'Do you want to send the argument?' in child_output:        x.stdin.write(b'yesn')        x.stdin.flush()x.stdout.close()x.stdin.close()

You’re assuming

child.exe
(in your mockup demo,
python.exe
) is
communicating with
main.py
via
sys.stdin/stdout
, however these I/O’s are
used to communicate with the shell that spawned the process.

很像childs的“stdout/stdin”将与
产生了这个过程,在本例中是“Popen()”。
每个派生的子进程

子流程.Popen(…)
将与
它有自己的“stdout/stdin/stderr”,否则每个子进程都会产生巨大的
你的主要进程的混乱。这意味着你必须检查
在该特定子进程上输出并相应地写入,如中所做
上面的例子。
一种看待它的方式是:![输入图像描述]
[这里](https://i.stack.imgur.com/L2QWa.png)
你要开始了
主.py
,并通过
系统标准输出
以及
标准输入
. 中的每个
input()``主.py
将输出某些内容到
系统标准输出

这样你就可以读了。
同样的逻辑也适用于
子.exe
where every
input()

输出一些东西到它的
系统标准输出
但请记住-
sys
不是共享的
过程间的变量)。

import sysif sys.argv[1] == 'start':    inp = input('Do you want to send the argument?n').lower()    if inp == 'no':        sys.exit()    elif inp == 'yes':        #Somehow send '1' to the stdin of 1.py while it is running        sys.stdout.write('1')        sys.stdout.flush()

但是一个简单的’print(1)

也会这样做,因为它基本上是输出的“1”到
系统标准输出`为了你。
编辑2018:不要忘记关闭输入和输出,因为它们可能会离开
打开文件系统描述符
晚年的问题。

其他信息传递者

假设您控制了要

子.exe
你可以修改
无论如何,其他一些选项包括:
套接字—使用常规套接字进行通信,在nix上,最有效的是Unix套接字。

更小心的尾巴!

.readline()
将假定数据中的某个地方有一个
n
,很可能在末尾。我切换到
.readline()
有两个原因,
.read()
将挂起并等待’EOF’,除非您指定要读取的字节数(如果我不骑自行车的话)。为了能够阅读你需要合并的各种输出选择。选择()在你的代码中-或者在某种类型的缓冲区中,你调用
x。标准读取(1)
一次读一个字节。因为如果您尝试读取
.read(1024)
并且缓冲区中没有1024个字节,那么您的读取将挂起,直到有1024个字符为止。
我在你的房间里留了个虫子
儿童.py
专门编写代码(我的作品)-这是一个简单的基本Python-希望这是一个如何调试错误的学习经验(你提到你不擅长它,这是一个学习的方法)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624377.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号