running non-python progs from python

Fredrik Lundh fredrik at pythonware.com
Tue Dec 9 06:43:59 EST 2003


"Spiffy" wrote:

> > How can I run this other program from a python script and pass the
> filename
> > as a parameter?
>
>     import os
>
>     filename = "myfile"
>     os.system("program %s" % filename)
>
> </F>
>
> Fredrik, the example you provided is virtually the same as the one from the
> "Learning Python" book.

that indicates that it's supposed to work, don't you think?

> When I run it, the dos command line appears with the message 'Bad command
> or file name".

that indicates that Windows cannot find the command, don't you think?

> Both the .exe and the .mid file are in the python path and the spelling has
> been checked.

you mean sys.path?  that's the problem, most likely.  As mentioned in the
documentation, os.system() executes the command just as if you've typed
it in a "DOS box".  Windows doesn't look at the Python path when you do
that, so to make sure Windows finds the command, you have to add it to
the Windows path (the PATH environment variable), or provide the full path
to os.system().

    program = r"x:\full\path\to\program"
    filename = "..."
    os.system("%s %s" % (program, filename))

the os.path.abspath() function can be useful in cases like this; it makes sure
that if your program can find a file, another program can also find it:

    program = os.path.abspath("x:/somewhere/program")
    filename = os.path.abspath("somefile")
    os.system("%s %s" % (program, filename))

(if the filename may contain spaces, you may have to add quotes around
the second %s)

the relevant manual page contains more information on os.system, and
mentions a couple of alternatives (os.startfile, os.spawnlp, etc):

    §http://www.python.org/doc/current/lib/os-process.html

> Pardon me for being a newbie, but if you don't have an answer, why do you
> have to give me attitude?

os.system() is still the answer; the problem is in how you used it and what
you expected from it, not in the function itself.  You cannot expect people
to read your mind, and then complain when they fail.

</F>








More information about the Python-list mailing list