【问题标题】:Got different result when using subprocess.popen and subprocess.run使用 subprocess.popen 和 subprocess.run 时得到不同的结果
【发布时间】:2020-11-30 21:13:07
【问题描述】:

当我执行下面的程序时,它会正确列出文件。

import subprocess


foo = subprocess.run("ls /home/my_home", 
                     shell=True, 
                     executable="/bin/bash", 
                     stdout=subprocess.PIPE, 
                     stdin=subprocess.PIPE, 
                     stderr=subprocess.PIPE)
my_std_out = foo.stdout.decode("utf-8")

但是当执行下面的程序时,stdout里面什么都没有。

import subprocess


foo = subprocess.Popen(["ls /home/my_home"], 
                       shell=True, 
                       executable="/bin/bash", 
                       stdout=subprocess.PIPE, 
                       stdin=subprocess.PIPE, 
                       stderr=subprocess.PIPE)
my_std_out = foo.stdout.read().decode("utf-8")

我想知道我的第二部分程序有什么问题吗?
提前谢谢你!

【问题讨论】:

  • 您的代码原样无效,因为以下行:executable=/bin/bash。你打算把它放在引号里吗?

标签: python python-3.x shell subprocess


【解决方案1】:

来自 python 文档: “communicate() 返回一个元组 (stdout_data, stderr_data)。如果流以文本模式打开,则数据将为字符串;否则为字节。” 因此,如果您想通过 Popen 获取输出,则必须像这样从communicate() 中解压缩重新生成的元组:

out, err = foo.communicate()
In [150]: out
Out[150]: b''
In [151]: err
Out[151]: b"ls: cannot access '/home/my_home': No such file or directory\n"

【讨论】:

    【解决方案2】:

    我认为当你使用如下括号时,bash 命令和路径应该放在引号之间

    import subprocess foo = subprocess.Popen(["ls", "/home/my_home"], shell=True, executable=/bin/bash, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) my_std_out = foo.stdout.read().decode("utf-8")
    

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 1970-01-01
      • 2017-01-04
      • 2018-11-21
      • 2023-03-19
      • 2019-12-23
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      相关资源
      最近更新 更多