Python 正在写入stdin,访问被拒绝

Python 正在写入stdin,访问被拒绝,python,stdin,Python,Stdin,我正在尝试编写一个python脚本来启动一个子进程,并写入子进程stdin。对输出进行一些测试,然后将更多命令写入stdin 我试过: def get_band(): print "band" p = subprocess.Popen(["/path/to/program","-c","-"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) ran_stdout = p.c

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

我试过:

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.
从Linux shell运行该工具允许附加选项,具体取决于为命令提供的选项。方案如下:
-h显示有关该命令的帮助
-c不是以交互方式从用户获取键入的命令,而是从命名文件(即批处理模式)读取命令。处理完所有命令后,CLI会话将自动结束。
-c-如上所述,但从LinuxStdin读取命令。这允许命令通过管道传输到程序。

如果您能告诉我们更多关于该程序的信息,也许了解该程序的人可以尝试更好地解释它是如何工作的

然而,你所描述的

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

与您的代码不匹配

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

为了弄清楚这一点,
p.communicate()
将它得到的所有内容写入子进程,关闭它的stdin,并从stdout和stderr读取它得到的任何内容

因此,它与你的愿望是不相容的:写,读,再写

所以你必须自己动手制作

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

但是要注意!不要读得太多,否则你的阅读可能会受阻

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


如果你需要更多关于其中一个或另一个的信息,这里有其他的答案,涵盖了这些主题。前几天我写了一篇文章。

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

  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分钟。