Python3,带有shell参数的subprocess.Popen反向工作

时间:2017-07-12 12:38:04

标签: python

我遇到一个问题:

call subprocess.Popen('adb shell ls', shell=True)  # has NO console output

call subprocess.Popen('adb shell ls', shell=False) # has console output

结果与我研究的结果相反。

任何人都知道shell参数会发生什么? 谢谢!

env:在64位Windows 7上的64位Python 3.6上。

1 个答案:

答案 0 :(得分:0)

注意: 来自docstring:" shell:如果为true,则命令将通过shell执行。"

"壳"参数不是处理控制台输出。如果命令(第一个参数)是“shell”/“bash”/ etc的类型,类似于“#!/ bin / bash”定义为脚本文件的第一行。

使用“subprocess”获取执行的流程输出有几个选项:

  1. 从进程对象读取输出,“stdout”文件类型成员 - 使用stdout = subprocess.PIPE:
  2. In [2]: proc = subprocess.Popen("ls /tmp/dir1", shell=True, 
                stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    In [3]: proc.poll()
    Out[3]: 0
    In [4]: proc.stdout
    Out[4]: <open file '<fdopen>', mode 'rb' at 0x105e06f60>
    In [5]: print proc.stdout.read()
    file1
    file2
    output1
    
    1. 从您自己的文件类型对象中读取输出 - 通过您自己的STDOUT文件对象:
    2. In [6]: with open("/tmp/dir1/output1", "wt") as stdout_file:
         ...:     proc = subprocess.Popen("ls /tmp/dir1", shell=True, stdout=stdout_file, stderr=subprocess.PIPE)
         ...:     while proc.poll() is None:
         ...:         pass
         ...:     
      
      In [7]: with open("/tmp/dir1/output1", "rt") as stdout_file:
         ...:     print stdout_file.read()
         ...:     
      file1
      file2
      output1
      
      1. 使用默认“stdout” - 类似于“os.system”上的输出 - 到控制台。 (可能你在寻找什么)
      2. In [8]: proc = subprocess.Popen("ls /tmp/dir1", shell=True)
        
        In [9]: file1 file2   output1
        

        有关更多选项,请参阅docstring。