2013-04-09 59 views
0

我想写一个启动子进程的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) 

然而print语句给出:

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. 
+3

消息是否可以由子进程生成? – Bogdacutu 2013-04-09 16:15:03

+0

是的,谢谢你,我想知道为什么会这样以及如何获得许可?如果我使用这些参数从终端运行进程,它运行良好。 – Paul 2013-04-09 16:19:33

回答

1

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

不过,你描述

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

与您的代码不符。

你的代码打印一些东西给我们自己的stdout,显示band,然后与子进程进行“一次性”通信。

为了清楚起见,p.communicate()写入了子进程的所有内容,关闭它的stdin并读出从stdout和stderr得到的所有内容。

因此它与您的愿望不符:写,读,写再次。

所以你必须自己制作。

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

但请注意!不要读得比你真正拥有的更多,否则你的阅读可能会受阻。

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

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

+0

以下我认为我的解决方案非常简单。 – Paul 2013-04-10 10:50:14

0

由于某种原因,这个工作方式在同一行传入命令。然后为每个我想要的命令调用这个函数。

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

如果你在cmdline上给cmd,可能你甚至可以省略'-c','-''。这取决于被调用的程序。除此之外,如果您对每个发出的命令都有单独的子进程是可以的,那么这可能是最简单的解决方案。 – glglgl 2013-04-10 11:20:38

+0

所有权利感谢,仍然接受你的伟大答案:)是的,这是好的,现在我只需要在后台运行它们,因为一些输出需要10分钟才能发生。 – Paul 2013-04-10 11:22:27