【发布时间】:2016-06-01 05:51:24
【问题描述】:
我必须要文件,main.py 和 child.py。
我正在尝试向 main.py 的标准输入发送一个字符串。
这是我不完整的代码:
main.py
from subprocess import *
import time
def main():
program = Popen(['python.exe'. 'child.py', 'start'])
while True: #waiting for'1' to be sent to the stdin
if sys.stdin == '1':
print('text)
if __name__ == '__main__':
main()
child.py
import sys
if 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
我不知道该怎么做。
我正在使用 python 3.5.1 运行 Windows 10
-谢谢
编辑: 当我将参数发送回 main.py 时,我无法重新打开程序。 os.system 重新打开对我来说没用的程序。
这些程序是我正在尝试做的一个小演示。在我的实际程序中,我无法做到这一点,因为这两个程序正在相互“交流”,需要始终打开。
我需要回答的是一种向 main.py 发送参数的方法,可能使用标准输入,但是当我发送参数时,它无法重新打开程序。像 os.system 这样的一些例子重新打开程序,这不是我想要做的。我需要一直打开 main.py。
我的新当前代码不起作用。弹出一个窗口,然后关闭。
main.py
from subprocess import Popen, PIPE, STDOUT
x = Popen(['python.exe', '2.py', 'start'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
while x.poll() is None:
if b'Do you want to send the argument?' in x.stdout.read():
x.stdin.write(b'yes\n')
child.py
import sys
import time
time.sleep(1)
if 1 = 1:
inp = input('Do you want to send the argument?\n').lower()
if inp == 'no':
sys.exit()
elif inp == 'yes':
sys.stdout.write('1')
sys.stdout.flush()
这是我的代码。
【问题讨论】:
-
为什么不直接做
import child? -
一般问题:您为什么要这样做?上下文是什么?
-
@VikasMadhusudana 不,不是:
Popen已经在这里做到了。这是关于将标准输出传递给另一个程序的标准输入(在这种情况下是父程序),在 *nix 语法中是与 shell 相关的,而不是真正的 Python。 -
我使用这个程序的方式,我不能只导入孩子。 @Torxed
-
main.py 和 child.py 的样子,是的,你可以,因为 child 会从父级继承
sys.argv,还有其他方法可以使用自定义参数和全局变量进行常规 python 导入。
标签: python python-3.x stdin