此问题已经在这里有了答案:
我正在尝试从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
结合使用?
这里的问题是您没有外壳,因此通配符不会扩展。
您可以使用
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)