简体   繁体   中英

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

I think that's should work. I want to get output of this command "grep -l %s *.py" % tag for each tag, on created file with tag name.

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()

But all what I see when script is runned - it's output in my console.

Use the subprocess module of Python

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

The documentation contains extensive documentation and examples.

The other (poor) option with os.system() is redirecting the output to a file

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

and then later reading the output file from within Python. However this is ugly and likely not very portable.

The most minimal change I can think of so you can get at the output in python is to change:

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

for:

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

This way, the output of the command will end up in the output variable.

I'm not sure why other people dogmatically tell you to change your code to use subprocess; it will need more rewriting to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM