【问题标题】:Input to process using Python使用 Python 处理的输入
【发布时间】:2013-10-03 18:41:10
【问题描述】:

我有一个通常从终端运行的命令(Say foo),如下所示:

    user@computer$ foo
    enter the string: *(here I enter some string)*
    RESULT OF THE COMMAND WITH THE GIVEN INPUT

我事先知道我需要提供什么意见。那么,如何使用此 python 代码自动调用:

   from subprocess import call
   call(['foo'])

如何自动输入 foo ?

【问题讨论】:

  • call([input('Enter the string')]) 在 Python 3.x 中,或call([raw_input()]) 在 Python 2.x 中
  • 这与 foo 无关。我怎么称呼它?
  • @user1928721 不要使用上面评论中的方法。这不是你想要的。

标签: python process subprocess


【解决方案1】:

您可以查看第三方pexpect模块(Here is the API):

import pexpect
child = pexpect.spawn('foo')
child.expect('enter the string:')
child.sendline('STRING YOU KNOW TO ENTER')
child.close() # End Communication

【讨论】:

    【解决方案2】:

    使用Popencommunicate

    from subprocess import Popen, PIPE
    
    process = Popen('foo', stdout=PIPE, stderr=PIPE)
    
    (stdout, stderr) = process.communicate("YOUR INPUT HERE")
    
    print stdout
    

    【讨论】:

    • 这似乎不起作用。我仍然得到提示,现在剩下的代码,即给定输入的命令结果似乎不起作用
    • @user1928721 "似乎不起作用" 更具体。这就像去看医生并说“我受伤了”并期望他们为您诊断。准确说明什么不起作用。你看到什么输出?你得到什么行为?你期待什么?
    • 我最诚挚的歉意。我对 python 和 linux 编程的整个世界都是新手。我收到输入提示(即“输入字符串:”),它在那里持续了超过一分钟,所以我假设自动输入没有发生并手动输入输入。其余代码似乎根本没有运行(即光标只在那里停留了 10 分钟,我终止了该进程,因为它通常会在几秒钟内给我结果(“给定输入的命令结果”)
    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多