简体   繁体   English

Python-一个接一个地执行多个Shell命令

[英]Python - Executing multiple shell commands one after another

I want to execute multiple shell commands one after another. 我想一个接一个地执行多个shell命令。 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. 使用subprocess.Popen我能够执行命令并获得输出。 But if i want to execute cd MyDIR and then ls -l . 但是,如果我要执行cd MyDIR ,然后执行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. 如果我将其执行为2行代码,则会得到父目录的文件列表,而不是cd进入的目录。 Using cd MyDIR && ls -l gives the required result. 使用cd MyDIR && ls -l提供所需的结果。 If i use the communicate method, i am not getting any result and also the stdin gets closed. 如果我使用communication方法,则不会得到任何结果,并且stdin也将关闭。 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. 这里给出的解决方案与python中的bash交互并不能解决我的问题,因为我想让shell尽可能长并根据需要保持活动状态。 Trying the solution on that pages gives a message that IO operation on closed file. 在该页面上尝试解决方案将显示一条消息, 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 这是源http://eyalarubas.com/python-subproc-nonblock.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM