writing to stdin, access denied

早过忘川 提交于 2019-12-13 07:35:20

问题


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.

I have tried:

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)

However the print statement gives:

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.

回答1:


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

Nevertheless, what you describe

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

does not match your code.

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

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.

So you'll have to craft that on your own.

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.

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

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.




回答2:


This worked for some reason, passing in the command in the same line. Then call this function for every command I want.

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


来源:https://stackoverflow.com/questions/15906833/writing-to-stdin-access-denied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!