python - 如何在 python 中运行这个 shell 脚本?

标签 python bash shell subprocess popen

我想从 python 程序运行 bash 脚本。该脚本有这样的命令:

find . -type d -exec bash -c 'cd "$0" && gunzip -c *.gz | cut -f 3 >> ../mydoc.txt' {} \;

通常我会运行一个子进程调用:

subprocess.call('ls | wc -l', shell=True)

但由于引号的缘故,这在这里是不可能的。有什么建议吗?

谢谢!

最佳答案

虽然问题已经得到解答,但我仍然会插话,因为我假设您想要执行该 bash 脚本,因为您没有功能等效的 Python 代码(基本上少于 40 行,见下文)。 为什么这样做而不是 bash 脚本?

  • 您的脚本现在可以在任何具有 Python 解释器的操作系统上运行
  • 功能更易于阅读和理解
  • 如果您需要任何特殊的东西,调整您自己的代码总是更容易
  • 更像 Pythonic :-)

请记住(作为您的 bash 脚本)没有任何类型的错误检查,输出文件是一个全局变量,但可以轻松更改。

import gzip
import os

# create out output file
outfile = open('/tmp/output.txt', mode='w', encoding='utf-8')

def process_line(line):
    """
    get the third column (delimiter is tab char) and write to output file
    """
    columns = line.split('\t')
    if len(columns) > 3:
        outfile.write(columns[3] + '\n')

def process_zipfile(filename):
    """
    read zip file content (we assume text) and split into lines for processing
    """
    print('Reading {0} ...'.format(filename))
    with gzip.open(filename, mode='rb') as f:
        lines = f.read().decode('utf-8').split('\n')
        for line in lines:
            process_line(line.strip())


def process_directory(dirtuple):
    """
    loop thru the list of files in that directory and process any .gz file
    """
    print('Processing {0} ...'.format(dirtuple[0]))
    for filename in dirtuple[2]:
        if filename.endswith('.gz'):
            process_zipfile(os.path.join(dirtuple[0], filename))

# walk the directory tree from current directory downward
for dirtuple in os.walk('.'):
    process_directory(dirtuple)

outfile.close()

关于python - 如何在 python 中运行这个 shell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45697389/

相关文章:

bash - 使多个命令出现在同一输出行

python - 在 Python 中嵌套三元运算符

python - 如何限制在构造函数之外设置属性?

bash shell 脚本 for 循环中的两个变量

java Runtime.exec 运行 shell 脚本 - 无法打开文件

bash - 测试命令选项是否被支持

linux - 如何对 Mutt 进行编程以在收到新电子邮件时采取行动?

python - boto3 aws api - 列出可用的实例类型

python - 使用 python 的 Splunk REST Api : 201 with curl, 404?

bash - 上传时自动公开文件的 AWS S3 命令