I want to execute multiple shell commands one after another. The commands are received from a remote device through socket. What i need to do is to create a shell that is accessible remotely. With subprocess.Popen
i am able to execute commands and get output. But if i want to execute cd MyDIR
and then ls -l
. If I execute it as 2 lines of code, i get file listing of the parent directory rather than the the directory i cd into. Using cd MyDIR && ls -l
gives the required result. If i use the communicate method, i am not getting any result and also the stdin gets closed. Can someone help me with a piece of code?
Edit
The solution given here Interacting with bash from python doesn't solve my problem as i want to keep the shell active as long as possible and as much as needed. Trying the solution on that pages gives a message that IO operation on closed file.
This code helps
from subprocess import Popen, PIPE
from time import sleep
from fcntl import fcntl, F_GETFL, F_SETFL
from os import O_NONBLOCK, read
# run the shell as a subprocess:
p = Popen(['python', 'shell.py'],
stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False)
# set the O_NONBLOCK flag of p.stdout file descriptor:
flags = fcntl(p.stdout, F_GETFL) # get current p.stdout flags
fcntl(p.stdout, F_SETFL, flags | O_NONBLOCK)
# issue command:
p.stdin.write('command\n')
# let the shell output the result:
sleep(0.1)
# get the output
while True:
try:
print read(p.stdout.fileno(), 1024),
except OSError:
# the os throws an exception if there is no data
print '[No more data]'
break
Here is the source http://eyalarubas.com/python-subproc-nonblock.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.