【发布时间】:2016-10-02 22:48:10
【问题描述】:
我正在努力从 bash shell 转换为 python3。
这是我要转换为 python 的 shell 命令:
cat $outDir/aDir/* | cut -f2 | sort -u > $outDir/outFile.txt
我已经使用了subprocess.call(),它可以工作,但我想知道如何使用 Popen() 来实现。
这是我的代码不起作用:
import subprocess
import glob
filePath = outDir + 'aDir/*'
outFilePath = outDir + '/outFile.txt'
fileList = []
for files in glob.glob(filePath):
fileList.append(files)
with open(files, 'r') as inFile, open(outFilePath, 'w') as outFile :
p = subprocess.Popen(['cat'], stdin=inFile, stdout=subprocess.PIPE)
p2 = subprocess.Popen(['cut', '-f2'], stdin = p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(['sort', '-u'], stdin = p2.stdout, stdout = outFile)
你能解释一下为什么shell=True 是有害的吗?我在很多答案中看到它,但不知道为什么......
谢谢。
【问题讨论】:
-
stackoverflow.com/questions/3172470/… 解释了为什么要避免使用
shell=True。 -
@tripleee: 和 @tripleee: 和 this shows that
shell=Truecan be useful(如果没有不受信任的输入,那么在直接使用subprocess.Popen重新实现 shell 管道时出错的可能性更大,而不是由于不兼容而导致错误对于一个简单的 shell 命令)。 -
问题不在于它没用,而在于使用它需要理解。不幸的是,Shell 拥有的用户甚至比 PHP 和 VBscript 的总和还要多,他们甚至不知道绝对的基础知识。 (这个问题在这方面明显高于平均水平。)
标签: python bash shell subprocess popen