gpt4 book ai didi

python - 使用 subprocess.Popen() 从 bash shell 转换为 python3

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:22 26 4
gpt4 key购买 nike

我正在努力从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com