0

我认为这应该有效。我想在创建的带有标签名称的文件上为每个标签获取此命令 "grep -l %s *.py" % 标签的输出。

import os
import sys

results_dir = '/home/ks/one/work/tn/format-description 15852/results'
converters_dir = '/home/ks/one/work/cvr'
export_dir = '/home/ks/one/work/epr'
all_dirs = {'cvr':cvrs_dir, 
            'epr':eprs_dir}

tags = [tag.strip() for tag in open('new file').readlines()]
for coe, directory in all_dirs.items(): # coe - type of our file
    os.chdir(results_dir)
    for tag in tags:
        tag_file = open(coe + ' ' + tag, 'w')
        sys.stdout = tag_file
        os.chdir(directory)
        os.system("grep -l %s *.py" % tag)
        tag_file.close()

但是我在运行脚本时看到的所有内容 - 它都在我的控制台中输出。

4

2 回答 2

2

使用 Python 的 subprocess 模块

http://docs.python.org/library/subprocess.html

该文档包含大量文档和示例。

os.system() 的另一个(差)选项是将输出重定向到文件

os.system('do_something >/tmp/myoutput')

然后从 Python 中读取输出文件。然而,这很丑陋并且可能不是很便携。

于 2012-09-05T08:16:23.487 回答
0

我能想到的最小更改是更改:

os.system("grep -l %s *.py" % tag)

为了:

output = commands.getoutput("grep -l %s *.py" % tag)

这样,命令的输出将最终出现在输出变量中。

我不确定为什么其他人教条地告诉您更改代码以使用子流程;这样做需要更多的重写。

于 2012-09-05T08:20:27.433 回答