I am trying to run a shell from my python program. I have used a mltithreaded approach where an input from user is accepted and should be executed via the shell.
Everything seems right, except that the program execution just doesn't take place beyond stdin.
I am not sure if there is something wrong with the way I have used Popen.stdin.
So please help on what is wrong here.
from subprocess import Popen,PIPE
import shlex
import threading
from Queue import Queue
class MyThread(threading.Thread):
def __init__(self,func,args):
threading.Thread.__init__(self)
self.func=func
self.args=args
def run(self):
apply(self.func,self.args)
开发者_如何学编程
def bash(command,output):
commandList=shlex.split('python test.py')
process=Popen(commandList,stdout=PIPE,stdin=PIPE,stderr=PIPE,shell=True)
print process.stdout.readlines()
while (process.pole()==None):
#commandList=shlex.split(command.get(1))
print 'bash'
process.stdin.write(command.get(1))
process.stdin.flush()
output.put(process.stdout.readlines(),1)
process.stdout.flush()
def communicate(command,output):
while True:
command.put(raw_input('enter command>'))
print 'communicate'
print output.get(1)
funcs=[bash,communicate]
nfuncs=len(funcs)
def main():
command=Queue(1)
output=Queue(1)
threads=[]
for i in range(nfuncs):
t=MyThread(funcs[i],(command,output))
threads.append(t)
for i in range(nfuncs):
threads[i].start()
for i in range(nfuncs):
threads[i].join()
print 'successful'
if __name__=='__main__':
main()
I have given the output below.
karthik@ubuntu:~/TerminalChatBot/test$ python threadTerminal.py
enter command>ls
communicate
After this there is no execution. I can't even use ctrl+c to stop the python script. It just hangs.
NOTE: the thread communicate needs to be there as we need to integrate this code with the bigger module.
Minor things:
It's process.poll()
not process.pole()
.
Instead of
for i in range(nfuncs):
t=MyThread(funcs[i],(command,output))
threads.append(t)
do
for func in nfuncs:
t=MyThread(func,(command,output))
threads.append(t)
Now, why are you running python test.py
? Don't you want to run ls communicate
in a shell, in which case you should be doing something like:
def bash(command,output):
process=Popen('bash',stdout=PIPE,stdin=PIPE,stderr=PIPE,shell=True)
print process.stdout.readlines()
# I don't really understand what's going on here
while (process.pole()==None):
print 'bash'
process.stdin.write(command.get(1))
process.stdin.flush()
output.put(process.stdout.readlines(),1)
process.stdout.flush()
could it be that it keeps hanging on process.stdout.readlines()
? Perhaps no line ending can be found. Try stdout.read(1) to read one character and see what happens.
精彩评论