2

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!

yosukesabai
  • 6,184
  • 4
  • 30
  • 42
user1551817
  • 6,693
  • 22
  • 72
  • 109

6 Answers6

9

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)
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • 1
    Oh I like that more than my solution. `with` rocks. +1 – tMC Sep 06 '12 at 05:33
  • Is that different than out=open('output.txt','w') ? – dooderson Sep 10 '14 at 18:53
  • 1
    @user1311069: I used the context manager interface of the file object. See, for example, the first example here http://eigenhombre.com/2013/04/20/introduction-to-context-managers/ or here http://preshing.com/20110920/the-python-with-statement-by-example/ – Warren Weckesser Sep 10 '14 at 19:19
  • This worked but in the ipython notebook the terminal no longer pumps out information. Any idea why? – John M Mar 15 '15 at 00:22
5

I believe this does what you want. Argument to os.system() should be a string representing command to the OS.

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

There is subprocess module, which may worth look into if you are planning to process the output further in python.

yosukesabai
  • 6,184
  • 4
  • 30
  • 42
4

Its better to use subprocess module that os.system

import subprocess
subprocess.call(['pdv', '-t', filename, '>', dest_file_name])
Rakesh
  • 81,458
  • 17
  • 76
  • 113
4
from subprocess import Popen
proc = Popen(['pdv', '-t', epoch_name], stdout = open('123.txt', 'w'))
tMC
  • 18,105
  • 14
  • 62
  • 98
1

See if the command script is available to you. It might do what you need.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

Or you can use sys.stdout check this document from DiveIntoPython or the discussion here if it helps you out.

import sys

print 'Dive in'
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout = fsock
print 'This message will be logged instead of displayed'
sys.stdout = saveout
fsock.close()
techDiscussion
  • 89
  • 3
  • 12