簡體   English   中英

在我的python腳本中我做錯了什么來獲得輸出?

[英]What did I do wrong in my python script to get output?

我認為這應該有效。 我想在帶有標簽名稱的創建文件上為每個標簽輸出此命令“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()

但是我在運行腳本時看到的所有內容 - 它都是在我的控制台中輸出的。

使用Python的子進程模塊

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

該文檔包含大量文檔和示例。

os.system()的另一個(差)選項是將輸出重定向到文件

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

然后從Python中讀取輸出文件。 然而,這是丑陋的,可能不是很便攜。

我能想到的最小的變化,所以你可以在python中得到輸出是改變:

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

對於:

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

這樣,命令的輸出將以輸出變量結束。

我不確定為什么其他人教條地告訴你更改代碼以使用子進程; 它需要更多的重寫才能這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM