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

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?


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()

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


import subprocess

proc = subprocess.Popen(['unison', 'profile'], stderr=subprocess.PIPE,      
                        stdout=subprocess.PIPE, stdin=subprocess.PIPE)

proc.stdin.write('user input')
print proc.stdout.read()

This should help you get started. Please edit your question with more information if you want a more detailed answer!

链接地址: http://www.djcxy.com/p/77152.html

上一篇: Raspberry Pi:终止来自python的raspistill命令

下一篇: python作为“批处理”脚本(即从python运行命令)