如何在python3子进程中使用Unix正则表达式字符? [重复]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

我正在尝试从Python3程序中的shell命令获取输出。我一直在看documentation,这就是我一直在处理的内容:

sortered=subprocess.run(
    # ['sort', time.strftime("%Y")+'*', '|', 'uniq', '-u'],  # causes error did not understand * char
    #['ls', '-l'],  # worked fine
    ['sort', '2019*'],  # gives same error as before
    capture_output=True
)

运行脚本后,我得到此错误:

$ myscript.py
CompletedProcess(args=['sort', '2019*'], returncode=2, stdout=b'', stderr=b"sort: cannot read: '2019*': No such file or directory\n")
To_Downloadtest1.sh has been created successfully

如果我使用*正常运行命令,它将运行正常。

$ sort 2019*
a file.
a file.
this one is a.
this one is b.

该脚本从与2019开头的文件所在的目录中运行。

.
├── 2019-A.txt
├── 2019-B.txt
└── myscript.py

当我运行python脚本时,应该发生的情况是命令的输出应作为字符串放入变量中。这没有发生。我唯一从subprocess.run得到错误的原因是在命令中使用*。否则,我会从stdout正确获得subprocess.run。我尝试了ls -l作为测试,它可以正常工作。如何将*subprocess.run结合使用?

python-3.x bash subprocess
1个回答
0
投票

这里的问题是您没有外壳,因此通配符不会扩展。

您可以使用

sortered = subprocess.run('sort 2019*', shell=True, capture_output=True)

import glob
sortered = subprocess.run(['sort'] + glob.glob('2019*'), capture_output=True)

或者,当然,

import glob

lines = []
for file in glob.glob('2019*') as handle:
    lines.extend(handle.read())
sortered = sorted(lines)
© www.soinside.com 2019 - 2024. All rights reserved.