gpt4 book ai didi

Python subprocess.Popen 在 shell 命令作为参数时失败

转载 作者:行者123 更新时间:2023-12-01 05:08:32 24 4
gpt4 key购买 nike

与 subprocess.Popen() 作斗争 - 为什么第一个和第三个按预期工作,而第二个找不到任何多个文件或目录?错误信息是:

>ls: Zugriff auf * nicht möglich: Datei oder Verzeichnis nicht gefunden

英文翻译:

File not found or directory: access to * not possible

这是代码。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import subprocess

args = []
args.append ('ls')
args.append ('-al')

# First does work
cmd1 = subprocess.Popen(args)
cmd1.wait()

# Second does NOT work
args.append ('*')
cmd2 = subprocess.Popen(args)
cmd2.wait()


# Third does work
shellcmd = "ls -al *"
cmd3 = subprocess.Popen(shellcmd, shell=True )
cmd3.wait()

最佳答案

这是因为默认情况下 subprocess.Popen() 没有 shell 解释命令,因此 "*" 不会被扩展为所需的文件列表。尝试添加 shell=True 作为调用的最后一个参数。

另请注意the warning in the documentation关于不信任以这种方式处理用户输入。

关于Python subprocess.Popen 在 shell 命令作为参数时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24629122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com