【问题标题】:writing to stdin, access denied写入标准输入,拒绝访问
【发布时间】:2013-04-09 15:59:37
【问题描述】:

我正在尝试编写一个启动子进程并写入子进程标准输入的 python 脚本。对输出进行一些测试,然后将更多命令写入标准输入。

我试过了:

def get_band():
    print "band" 
    p = subprocess.Popen(["/path/to/program","-c","-"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

    ran_stdout = p.communicate(input='show status')[0]
    print(ran_stdout)

然而打印语句给出:

Unable to connect at 127.0.0.1, Connection refused. 

我想知道我这样做是否正确?这是有关我尝试运行的过程的文档。我想使用最后一个选项。

Running the tool from the Linux shell allows additional options, depending on the options given to the command. The options are as follows:

-h Displays help about the command

-c <Filename>  Instead of taking typed commands interactively from a user the commands are read from the named file, i.e. in batch mode. When all commands are processed the CLI session ends automatically.

-c - As above but reads command from Linux stdin. This allows commands to be ‘piped’ to the program.

【问题讨论】:

  • 子进程可以生成消息吗?
  • 是的,谢谢,我想知道为什么会这样以及如何获得许可?如果我使用这些参数从终端运行该过程,它运行良好。

标签: python stdin


【解决方案1】:

如果您能告诉我们有关该程序的更多信息,也许知道该程序的人可以尝试更好地解释它的具体工作原理。

不过,你所描述的

启动一个子进程,并写入子进程的标准输入。对输出进行一些测试,然后将更多命令写入标准输入。

与您的代码不匹配。

您的代码将某些内容打印到我们自己的标准输出,显示 band,然后与子进程进行“一次性”通信。

为了明确这一点,p.communicate() 将它获得的所有内容写入子进程,关闭其标准输入并读出它从 stdout 和 stderr 获得的所有内容。

因此它与你想要的不兼容:写,读,再写。

所以你必须自己制作。

如果您编写的块足够小以保证可以放入管道缓冲区,那很简单:只需编写命令(不要忘记结尾的 \n)并读取。

但请注意!阅读量不要超过实际阅读量,否则您的阅读可能会受阻。

因此,使用非阻塞 IO 或 select.select()

如果您需要有关其中一个或其他的更多信息,这里还有其他关于 SO 的答案,涵盖了这些主题。前几天我写了one which might help you

【讨论】:

  • 认为我下面的解决方案相当简单。
【解决方案2】:

这出于某种原因,在同一行中传递了命令。然后为我想要的每个命令调用这个函数。

  p = subprocess.Popen(["/path/to/program", '-c', '-', cmd_here],
  stdout=subprocess.PIPE) 
  proc_stdout, proc_stderr = proc.communicate()
  proc.wait()
  #print stuff

【讨论】:

  • 如果你在cmdline上给出cmd,你甚至可以省略'-c', '-'。这取决于被调用的程序。除此之外,如果您可以为每个发出的命令有一个单独的子进程,那么这可能是最简单的解决方案。
  • 好的,谢谢,仍然接受您的好回答 :) 是的,没关系,现在我只需要在后台运行它们,因为某些输出需要 10 分钟才能发生。
猜你喜欢
  • 2013-11-18
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
相关资源
最近更新 更多