写入标准输入,拒绝访问 [英] writing to stdin, access denied

查看:26
本文介绍了写入标准输入,拒绝访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a python script that starts a subprocess, and writes to the subprocess stdin. Does some tests on teh output and then writes more commands to 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. 

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

I was wondering if i am doing this right? Here is the documentation about the process I'm trying to run. I want to use the last option.

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.

推荐答案

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

If you could tell us more about that program, maybe someone knowing this program could try to explain better how it works in particular.

尽管如此,你所描述的

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

starts a subprocess, and writes to the subprocess stdin. Does some tests on teh output and then writes more commands to stdin.

与您的代码不匹配.

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

Your code prints something to our own stdout, displaying band, and then does a "one-shot" communication with the subprocess.

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

To be clear about that, p.communicate() writes all it gets to the subprocess, closes its stdin and reads out whatever it gets from stdout and stderr.

因此它与您的愿望不相容:写,读,再写.

Thus it is incompatible with what you desire: write, read, write again.

所以你必须自己制作.

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

If the chunks you write are small enough to be guaranteed to fit into the pipe buffer, it is simple: just write the commands (don't forget the trailing \n) and read.

但是要注意!阅读量不要超过实际阅读量,否则你的阅读可能会受阻.

But be aware! Don't read more than you really have, or your reading might block.

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

Thus, work with non-blocking IO or with select.select().

如果您需要有关其中一个或另一个的更多信息,SO 上还有其他答案,其中涵盖了这些主题.前几天我写了一个可能对你有帮助的.

If you need more information about the one or other, there are other answers here on SO which cover these subjects. The other day I wrote one which might help you.

这篇关于写入标准输入,拒绝访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆