14

I have a program that I run from the command line that looks like this:

$ program a.txt b.txt

The program requires two text files as arguments. I am trying to write a Python 3.2 script to run the above program. How can I do this? Currently, I am trying to use the subprocess module like this:

import subprocess

with open("a.txt", mode="r") as file_1:
    with open("b.txt", mode="r") as file_2:
        cmd = ['/Users/me/src/program', file_1, file_2]
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        for line in process.stdout:
            print(line)

I read this post and the post here, which seem to describe similar solutions to my problem. Unfortunately, after reading these posts, I still can't seem to make my Python code run my program.

Can anyone help? Thanks in advance!

Community
  • 1
  • 1
drbunsen
  • 8,781
  • 20
  • 62
  • 91

4 Answers4

23

Look at @Chris's answer, and also:

Subprocess doesn't wait for command to finish, so you should use wait method.

process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
process.wait()
for line in process.stdout:
    print(line)
Neuron
  • 3,776
  • 3
  • 24
  • 44
utdemir
  • 24,044
  • 9
  • 56
  • 78
21

subprocess.Popen expects an array of strings. Two of the items in that array are file handles. You need to pass the actual file name to the program you're trying to run.

cmd = ['/Users/me/src/program', 'a.txt', 'b.txt']

You can get rid of the with open(...) as ... lines completely.

Chris Eberle
  • 44,989
  • 12
  • 77
  • 112
  • Thank you for the help, I somehow missed that `subprocess.Popen()` requires strings not file handles. Your solution worked like a charm! – drbunsen Aug 04 '11 at 17:12
10

Depending on your requirements, os.system(cmdline) might be the simples solution.

Achim
  • 14,333
  • 13
  • 70
  • 128
1

Using subprocess.wait() with stdout=subprocess.PIPE is not recommended.

with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
    print(proc.stdout.read())

You don't have to call subprocess.wait(). This will print realtime stdout of proc and parent process will wait the termination of proc.

Check these urls for more information.

SHIM
  • 41
  • 2