【问题标题】:How to use subprocess.Popen with built-in command on Windows如何在 Windows 上使用带有内置命令的 subprocess.Popen
【发布时间】:2017-02-04 14:34:09
【问题描述】:

在我的旧 python 脚本中,我使用以下代码来显示 Windows cmd 命令的结果:

print(os.popen("dir c:\\").read())

正如 python 2.7 文档所说,os.popen 已过时,建议使用subprocess。我按照以下文档进行操作:

result = subprocess.Popen("dir c:\\").stdout

我收到错误消息:

WindowsError: [Error 2] The system cannot find the file specified

你能告诉我使用subprocess模块的正确方法吗?

【问题讨论】:

  • 请注意,Windows 上的 dir 内置在 shell 中,因此它不是独立的可执行文件 - 请参阅 stackoverflow.com/questions/20330385/…
  • @metatoaster 谢谢。看完帖子,我的理解是subprocess不能调用内置的shell命令。那么os.popen 在这种情况下是不是“过时”?

标签: python windows python-2.7 command-line subprocess


【解决方案1】:

您应该使用 call subprocess.Popenshell=True 如下:

import subprocess

result = subprocess.Popen("dir c:", shell=True,
                          stdout=subprocess.PIPE, stderr=subprocess.PIPE)

output,error = result.communicate()

print (output)

More info on subprocess module.

【讨论】:

  • shell=True 用于setdir 等内部shell 命令通常是个坏主意。输出使用有损 ANSI 编码。 Windows 环境变量和文件系统名称是 UTF-16,因此通常内部 shell 命令应该使用 /u /c 选项运行,以使 cmd 输出 UTF-16。然后必须将输出解码为'utf-16le'。无法使用 shell=True 完成此操作,因为 /c /u 的顺序错误。
【解决方案2】:

这适用于 Python 3.7:

from subprocess import Popen, PIPE

args = ["echo", "realtime abc"]
p = Popen(args, stdout=PIPE, stderr=PIPE, shell=True, text=True)

for line in p.stdout:
    print("O=:", line)

输出:

O=: "实时 abc"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2016-09-03
    • 2016-12-13
    • 2020-08-10
    • 2015-02-02
    相关资源
    最近更新 更多