我正在努力从 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 有害吗?我在很多答案中看到它,但不知道为什么...
谢谢。
请您参考如下方法:
您需要将文件列表传递给 cat 所以
subprocess.Popen(['cat'], stdin=inFile, stdout=subprocess.PIPE)
应该变成
subprocess.Popen(['cat'] + [fileList], stdout=subprocess.PIPE)
因此不再需要 inFile
总而言之
import subprocess
import glob
filePath = outDir + '/aDir/*'
outFilePath = outDir + '/outFile.txt'
fileList = glob.glob(filePath)
with open(outFilePath, 'w') as outFile:
subprocess.Popen(['cat'] + [fileList], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['cut', '-f2'], stdin = p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(['sort', '-u'], stdin = p2.stdout, stdout = outFile)
