【问题标题】:python fails to execute a windows command with findpython无法使用find执行windows命令
【发布时间】:2017-03-15 21:07:22
【问题描述】:

我要执行命令:

dir c: | find "File"

文件夹中的文件数。

没有

subprocess.call(['dir c: | find "File"'], shell=True)

subprocess.call(['dir', 'c:', '| find "File"'], shell=True)

有效。

Python 将命令翻译成

'"dir c: | find \"file\""'

导致失败。

有什么解决方法吗?

相关说明:http://www.cmi.ac.in/~madhavan/courses/prog2-2015/docs/python-3.4.2-docs-html/library/subprocess.html#notes

谢谢

【问题讨论】:

    标签: windows python-3.x cmd subprocess call


    【解决方案1】:

    首先,我无法从 Windows 中找到“dir”命令,因此无法使用“shell=False”执行该命令。 但它适用于

    os.chdir('C:')
    cdirszbuf = os.popen('dir | find "File"')
    cdirinfo = cdirszbuf.readlines()
    

    谢谢

    【讨论】:

    • 在 Python 3 中 os.popen 只需使用 shell=True 调用 subprocess.Popen 并将结果包装在类似文件的类中。另外,AFAIK,没有人告诉过你使用shell=False,我已经解释过dir 是一个内置的shell 命令。没有要执行的dir.exe。为此,您必须使用 shell 并支持命令行语法,例如 '|',以便在两个命令之间创建管道。
    【解决方案2】:

    如果您使用shell=True,则需要将命令作为字符串传递,该字符串在执行期间由shell(例如Windows 上的cmd)解释。仅当 shell=False 时才适用以列表形式传递参数。

    简单尝试:

    subprocess.call('dir c: | find "File"', shell=True)
    

    【讨论】:

    • 不幸的是,shell=false 失败,错误为:FileNotFoundError: [WinError 2] 系统找不到指定的文件
    • @69444091,但 Łukasz 告诉您使用 shell=True,除了使用字符串而不是列表。 subprocess.list2cmdline 不知道如何将参数列表转换为 cmd shell 命令行。至于获取FileNotFoundErrordir 是 cmd shell 中的内置命令。使用where.exe 命令来确定命令是外部可执行文件(例如xcopy.exe)还是内置于shell(例如copy)。
    猜你喜欢
    • 2019-09-28
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多