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()notprocess.pole().Instead of
do
Now, why are you running
python test.py? Don’t you want to runls communicatein a shell, in which case you should be doing something like: