Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to run another program?

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!

like image 555
drbunsen Avatar asked Aug 04 '11 16:08

drbunsen


People also ask

Can Python run other programs?

You can run other programs via functions in the os module or, in Python 2.4, by using the new subprocess module.

How do I use one file to another in Python?

Approach: Create a Python file containing the required functions. Create another Python file and import the previous Python file into it. Call the functions defined in the imported file.


2 Answers

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)
like image 66
utdemir Avatar answered Oct 13 '22 22:10

utdemir


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.

like image 26
Chris Eberle Avatar answered Oct 13 '22 23:10

Chris Eberle