【问题标题】:Python - Executing multiple shell commands one after anotherPython - 一个接一个地执行多个shell命令
【发布时间】:2017-05-28 21:58:32
【问题描述】:

我想一个接一个地执行多个shell命令。通过套接字从远程设备接收命令。我需要做的是创建一个可远程访问的外壳。使用subprocess.Popen,我能够执行命令并获得输出。但是如果我想执行cd MyDIR 然后ls -l。如果我将它作为 2 行代码执行,我会得到父目录的文件列表,而不是我 cd 进入的目录。使用 cd MyDIR && ls -l 可以得到所需的结果。如果我使用通信方法,我不会得到任何结果,并且标准输入也会关闭。有人可以帮我写一段代码吗?

编辑

Interacting with bash from python 这里给出的解决方案并不能解决我的问题,因为我想尽可能长时间地保持 shell 处于活动状态,并且尽可能多地处于需要状态。尝试该页面上的解决方案会给出一条消息,IO operation on closed file.

【问题讨论】:

  • @PatrickHaugh 是的,它看起来像重复,但我想解决 IO operation on closed file 错误。我想保持沟通活跃。
  • 如果你听 bash 的话,看起来会更容易。只需nc -k -l 4444 | bash
  • @Raz 我不能用nc -k -l 4444 | bash 听因为,bash 只是我想做的一部分。我实际上是在尝试使用 Telegram bot 运行 shell 命令。我将远程发送命令,机器人在我的 RPI 上执行它,它会将响应发回给我。这是我真正需要的。
  • 也许你可以启动 tmux 会话并与之交互。检查此lib。它可以连接到会话并执行pane.send_keys('echo hey send now')

标签: python shell subprocess


【解决方案1】:

这段代码有帮助

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

这里是来源http://eyalarubas.com/python-subproc-nonblock.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多