【问题标题】:Interacting with bash from python从 python 与 bash 交互
【发布时间】:2012-03-29 05:53:51
【问题描述】:

我一直在玩 Python 的 subprocess 模块,我想用 python 中的 bash 做一个“交互式会话”。我希望能够像在终端模拟器上一样从 Python 读取 bash 输出/写入命令。我想一个代码示例可以更好地解释它:

>>> proc = subprocess.Popen(['/bin/bash'])
>>> proc.communicate()
('user@machine:~/','')
>>> proc.communicate('ls\n')
('file1 file2 file3','')

(显然,它不是那样工作的。)这样的事情可能吗?如何?

非常感谢

【问题讨论】:

    标签: python bash subprocess


    【解决方案1】:

    试试这个例子:

    import subprocess
    
    proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout = proc.communicate('ls -lash')
    
    print stdout
    

    您必须阅读有关 stdin、stdout 和 stderr 的更多信息。这看起来不错的讲座:http://www.doughellmann.com/PyMOTW/subprocess/

    编辑:

    另一个例子:

    >>> process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    >>> process.stdin.write('echo it works!\n')
    >>> process.stdout.readline()
    'it works!\n'
    >>> process.stdin.write('date\n')
    >>> process.stdout.readline()
    'wto, 13 mar 2012, 17:25:35 CET\n'
    >>> 
    

    【讨论】:

    • 第一个 .communicate() 调用运行良好,但如果我再次尝试通信,就会发生这种情况:ValueError: I/O operation on closed file。有什么办法让它继续运行吗?
    • 1- 第一个代码示例可以写成stdout = subprocess.check_output(['ls', '-lash'])。要运行bash 命令,您可以check_output("some && command $(< file)", shell=True, executable='/bin/bash') 2- 第二个代码示例非常脆弱- 如果输入/输出不同步。可能会发生死锁。 3- 如果标准输入/标准输出不是 tty;该程序可能会更改其输出。见Q: Why not just use a pipe (popen())?
    • 您的“另一个示例”在 Python3.5 中不起作用。有什么办法解决吗?
    • @waitingkuo 这是因为在 Python 3 中 buffsize 默认为 -1 而在 2 中为 0,因此在 Popen 中将其设置为 0 并且它应该可以工作。对我来说确实如此。
    • 你的例子不是交互式shell,是静态指令执行。
    【解决方案2】:

    在我的另一个答案中使用这个例子:https://stackoverflow.com/a/43012138/3555925

    您可以在该答案中获得更多详细信息。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os
    import sys
    import select
    import termios
    import tty
    import pty
    from subprocess import Popen
    
    command = 'bash'
    # command = 'docker run -it --rm centos /bin/bash'.split()
    
    # save original tty setting then set it to raw mode
    old_tty = termios.tcgetattr(sys.stdin)
    tty.setraw(sys.stdin.fileno())
    
    # open pseudo-terminal to interact with subprocess
    master_fd, slave_fd = pty.openpty()
    
    # use os.setsid() make it run in a new process group, or bash job control will not be enabled
    p = Popen(command,
              preexec_fn=os.setsid,
              stdin=slave_fd,
              stdout=slave_fd,
              stderr=slave_fd,
              universal_newlines=True)
    
    while p.poll() is None:
        r, w, e = select.select([sys.stdin, master_fd], [], [])
        if sys.stdin in r:
            d = os.read(sys.stdin.fileno(), 10240)
            os.write(master_fd, d)
        elif master_fd in r:
            o = os.read(master_fd, 10240)
            if o:
                os.write(sys.stdout.fileno(), o)
    
    # restore tty settings back
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
    

    【讨论】:

      【解决方案3】:

      交互式 bash 进程期望与 tty 进行交互。要创建伪终端,请使用 os.openpty()。这将返回一个 slave_fd 文件描述符,您可以使用它来打开标准输入、标准输出和标准错误的文件。然后,您可以写入和读取 master_fd 以与您的进程进行交互。请注意,如果您要进行稍微复杂的交互,您还需要使用 select 模块来确保您不会死锁。

      【讨论】:

        【解决方案4】:

        我写了一个模块来方便*nix shell和python之间的交互。

        def execute(cmd):
        if not _DEBUG_MODE:
            ## Use bash; the default is sh
            print 'Output of command ' + cmd + ' :'
            subprocess.call(cmd, shell=True, executable='/bin/bash')
            print ''
        else:
            print 'The command is ' + cmd
            print ''
        

        在 github 上查看全部内容:https://github.com/jerryzhujian9/ez.py/blob/master/ez/easyshell.py

        【讨论】:

        • 你现在可以通过 pip 安装:pip install ez
        【解决方案5】:

        这应该是你想要的

            import subprocess
            import threading
            
            p = subprocess.Popen(["bash"], stderr=subprocess.PIPE,shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            exit = False
            
            def read_stdout():
                while not exit:
                    msg = p.stdout.readline()
                    print("stdout: ", msg.decode())
            def read_stderro():
                while not exit:
                    msg = p.stderr.readline()
                    print("stderr: ", msg.decode())
            
            threading.Thread(target=read_stdout).start()
            threading.Thread(target=read_stderro).start()
            
            while not exit:
                res = input(">")
                p.stdin.write((res + '\n').encode())
                p.stdin.flush()
        

        测试结果:

        >ls
        >stdout:  1.py
        
        stdout:  2.py
        
        ssss
        >stderr:  bash: line 2: ssss: command not found
        

        【讨论】:

          猜你喜欢
          • 2020-02-08
          • 1970-01-01
          • 1970-01-01
          • 2019-02-27
          • 2011-01-16
          • 2021-01-08
          • 2013-02-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多