python as a "batch" script (i.e. run commands from python)


Question

I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.

how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time.

So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file.

I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?!

basically, in a batch script I can write: unison profile

how can I achieve the same effect in python?

EDIT:

I found out it can be done with os.system( ... ) and since I cannot accept my own answer, I'm closing the question.


EDIT: this was supposed to be a comment, but when I posted it I didn't have much points.

Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment

>>> os.execlp("unison")

C:\>Usage: unison [options]
    or unison root1 root2 [options]
    or unison profilename [options]

For a list of options, type "unison -help".
For a tutorial on basic usage, type "unison -doc tutorial".
For other documentation, type "unison -doc topics".

C:\>
C:\>
C:\>

how to get around this?

1
10
9/1/2011 3:39:56 AM

Accepted Answer

I found out that os.system does what I want,

Thanks for all that tried to help.

os.system("dir")

runs the command just as if it was run from a batch file

6
11/23/2008 11:41:25 PM

You should create a new processess using the subprocess module.

I'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions.

EDIT: I maintain that you should prefer the Subprocess module to os.* OS specific functions, it is cross-platform and more pythonic (just google it). You can wait for the result easily, and cleanly:

import os
import subprocess
unison = os.path.join(os.path.curdir, "unison")
p = subprocess.Popen(unison)
p.wait()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon