calling another python file within python

Ben C spamspam at spam.eggs
Tue Mar 14 14:01:07 EST 2006


On 2006-03-14, Kevin <neurogasm at gmail.com> wrote:
> i have a python file called pyq which outputs stock quotes, currently i 
> also have a html file that takes stock ticker inputs, i would like to 
> bridge the two by building another program that takes the html inputs 
> and uses them to call the pyq stock ticker program and then output them 
> into a text file...
>
> any idea how to do this? my tentative code is:
>
>
>
> #!/usr/bin/python
>
> import os
> import urllib
> os.system("python pyq.py ibm > text1.txt")

Rather than invoke the shell (which is what system does), you can just
do it all from Python. Something like:

import pyq
pyq.run("ibm")

Then in pyq.py, you could have something like this:

def run(filename):
    # do whatever...

def main():
    # check args etc..
    run(sys.argv[1])

if __name__ == "__main__":
    main()

This way pyq would work from the shell if you wanted to run it that way,
and also as a module.

Not quite sure of the details of the input. If the other program is
creating this file ibm which you're immediately reading as soon as it
appears you'd probably be better off with a pipe.

See Python docs for the "socket" module. Or less portably and if you're
on a UNIX system you could use a named pipe (created with mkfifo).

> note: currently the text1.txt outputted is just blank, however if i
> run the command normally as 'python pyq.py ibm' in the command line,
> it works correctly and gives me the price of ibm.

If you launch pyq.py like this it has to be in the current working
directory of the other program. If you just go os.system("pyq.py ibm")
and pyq.py has the #! business at the start of it, then pyq.py has to be
in your PATH. Otherwise it should work. So long as you're sure the file
ibm has been created by this point.

One of the benefits of doing it with import instead (the thing I
described above) is you don't have to worry about the shell and its
environment, or what PATH is, but only the Python environment
(PYTHONPATH, sys.path, that kind of thing). It's more portable.



More information about the Python-list mailing list