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

标签 python bash shell subprocess popen

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

相关文章:

bash - 在 bash 中删除 CSV 文件列中的空格

mysql - 使用参数在 bash 中执行 .sql 文件

python - Pandas :从给定名称列表中获取列索引

python - 如何从 Pexels API 下载视频?

bash - VSCode : How to open two terminals on startup with different directories

bash - 如何选择版本号最高的文件名?

shell - 在 Ansible 中启动 Bitbucket 服务器

c# - 从 ASP.NET Core 3 应用程序执行 Linux Shell 命令

python - 使用 Python 进行捕食者-猎物模拟。 Python 读取等式错误的问题?

python - 避免对子类进行重复验证