linux - How to read python subprocess stdout without communicate -


i have python 3 script accepts input user, input piped subprocess, shell has been spawned. going put code socket, able make own non-serious remote administration tool, proves hard level currently. code:

import subprocess  p1 = subprocess.popen(["/bin/sh"], stderr = subprocess.pipe, stdin = subprocess.pipe, stdout = subprocess.pipe, encoding = "utf-8")  command = input("command: ")  p1.stdin.write(command)  p1.stdout.read() 

problem: nothing gets printed out. have searched endless hours online reason, on multiple days, of them don't seem work, and/or advise using communicate() not want do. when thinking ahead if able implement socket, can't have process closing after each command. have tried flushes everywhere, before write, inbetween read, after read, pretty everywhere can think of. should simple enough, without me having deep io module or rules of buffering (too late now). have been struggling days on end.

you have couple of issues, try draw path, hope not misleading you.

first of all, disclaimer: executing user input inherently unsafe. if that's not issue, let's keep on problem.

i start doing

p1 = subprocess.popen(["/bin/sh"], stderr=subprocess.pipe, stdin=subprocess.pipe, stdout=subprocess.pipe, universal_newlines=true, bufsize=1) 

having line-buffered pipe idea, in scenario.

then, remember have press enter after command, so:

command = input("command: ") + "\n" 

the write correct,

p1.stdin.write(command) 

but the, read dangerous , trivially become deadlocked. because stdout open (without eof or that) should read conservatively, , still, have problems on that.

a first idea read lines:

p1.stdout.readline() 

but, if don't know how many lines can read... that's problem. in fact, specific problem has been asked.

if want experiment, open interactive python interpreter, send "ls\n" command , perform readline(). work, until read last line, , then... wait forever. bad behaviour. need solve that.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -