如何与外部脚本(程序)交互
有一个需要键盘输入的脚本, 我可以在 python 中使用 os.system('./script') 调用该脚本,
如何从另一个调用脚本将输入发送回脚本?
更新:
脚本是:
$ cat script
#!/usr/bin/python
for i in range(4):
name=raw_input('enter your name')
print 'Welcome %s :) ' % name
当我尝试不使用 for 循环时,它可以工作,但仅在脚本退出时才显示输出。
>>> p = subprocess.Popen('./script',stdin=subprocess.PIPE)
>>> p.communicate('navras')
enter your nameWelcome navras :)
当我使用 foo 循环尝试它时,它会抛出错误,如何在使用新的打印语句更新 stdout 时交互式显示语句
>>> p.communicate('megna')
enter your nameWelcome megna :)
enter your nameTraceback (most recent call last):
File "./script", line 3, in <module>
name=raw_input('enter your name')
EOFError: EOF when reading a line
(None, None)
there is a script that expects keyboard input,
i can call that script with os.system('./script') in python,
how is it possible to send back an input to the script from another calling script?
update:
the script is:
$ cat script
#!/usr/bin/python
for i in range(4):
name=raw_input('enter your name')
print 'Welcome %s :) ' % name
when i try without a for loop, it works but it shows the output only when the script quits.
>>> p = subprocess.Popen('./script',stdin=subprocess.PIPE)
>>> p.communicate('navras')
enter your nameWelcome navras :)
when i try it with the foor loop, it throws error, How to display the statements interactive as and when the stdout is updated with new print statements
>>> p.communicate('megna')
enter your nameWelcome megna :)
enter your nameTraceback (most recent call last):
File "./script", line 3, in <module>
name=raw_input('enter your name')
EOFError: EOF when reading a line
(None, None)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 subprocess 而不是 os.system:
它不是 testet
You can use subprocess instead of os.system:
its not testet
事实上,os.system 和 os.popen 现已弃用,建议使用 subprocess 来处理所有子进程交互。
In fact, os.system and os.popen are now deprecated and subprocess is the recommended way to handle all sub process interaction.