如何与外部脚本(程序)交互

发布于 2024-09-10 04:19:21 字数 837 浏览 1 评论 0原文

有一个需要键盘输入的脚本, 我可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白鸥掠海 2024-09-17 04:19:21

您可以使用 subprocess 而不是 os.system:

p = subprocess.Popen('./script',stdin=subprocess.PIPE)
p.communicate('command')

它不是 testet

You can use subprocess instead of os.system:

p = subprocess.Popen('./script',stdin=subprocess.PIPE)
p.communicate('command')

its not testet

離殇 2024-09-17 04:19:21

事实上,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文