drakide
drakide

Reputation: 21

call program with arguments

i would like to start a python file (.py) with arguments and receive the output of it after it is finished. i have already heard about "popen" and "subprocess.call" but i could not find any tutorials how to use them

does anyone know a good tutorial?

Upvotes: 2

Views: 7790

Answers (4)

Guillaume Lebourgeois
Guillaume Lebourgeois

Reputation: 3873

You don't need them ; just launch your file as a program giving argument like

./main.py arg1 arg2 arg3 >some_file

(for that your file must begin with something like #!/usr/bin/env python)

Using sys module you can access them :

arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]

Upvotes: 6

remosu
remosu

Reputation: 5109

runme.py

print 'catch me'

main.py

import sys
from StringIO import StringIO

new_out = StringIO()
old_out = sys.stdout
sys.stdout = new_out

import runme

sys.stdout = old_out

new_out.seek(0)
print new_out.read()

and...

$ python main.py 
catch me

Upvotes: 1

S.Lott
S.Lott

Reputation: 391848

i would like to start a python file (.py) with arguments and receive the output of it after it is finished.

Step 1. Don't use subprocess. You're doing it wrong.

Step 2. Read the Python file you want to run. Let's call it runme.py.

Step 3. Read it again. If it's competently written, there is a block of code that starts if __name__ == "__main__":. What follows is the "external interface" to that file. Since you provided no information in the question, I'll assume it looks like this.

if __name__ == "__main__":
    main()

Step 4. Read the "main" function invoked by the calling script. Since you provided no information, I'll assume it looks like this.

def main():
    options, args = parse_options()
    for name in args:
        process( options, file )

Keep reading to be sure you see how parse_options and process work. I'll assume parse_options uses optparse.

Step 5. Write your "calling" script.

 import runme
 import sys
 import optparse
 options = options= optparse.Values({'this':'that','option':'arg','flag':True})
 with open( "theoutput.out", "w" ) as results:
     sys.stdout= results
     for name in ('some', 'list', 'of', 'arguments' ):
         runme.process( options, name )

This is the correct way to run a Python file from within Python.

Actually figure out the interface for the thing you want to run. And run it.

Upvotes: 5

Katriel
Katriel

Reputation: 123632

Unless you mean you want to start the Python file from within Python? In which case it's even nicer:

import nameOfPythonFile

Upvotes: 0

Related Questions