Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

python - writing terminal output to file

On my machine, I have some software which takes commands in the terminal and returns a list of values.

To run it, I have to type something like:

pdv -t filename

I am trying to run it as part of a python programme. When I run the following:

os.system('pdv -t %s' % (epoch_name))

then I get the values that I desire returned to my terminal (where epoch_name is the variable name for the filename). But when I try to write the result to a file:

os.system('pdv -t %s % "(epoch_name)" > 123.txt')

the file 123.txt is produced but it is empty.

I know that I am misplacing the " and/or ' characters, but I can't figure out where they should go.

Any help would be gratefully received!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use subprocess.call, with the stdout keyword argument:

import subprocess

cmd = ['ls', '-l']

with open('output.txt', 'w') as out:
    return_code = subprocess.call(cmd, stdout=out)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...