我正在努力从 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)
关于python - 使用 subprocess.Popen() 从 bash shell 转换为 python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37604722/