Running a file, with a relative filename

Michael P. Reilly arcege at shore.net
Tue May 11 10:28:02 EDT 1999


Phil Hunt <philh at vision25.demon.co.uk> wrote:

: I want to run a python program, where one module causes another Python
: module to execute, where the pathname of the second module is known 
: relative to the first module.

: i.e. I have:

:    ~/project/dev/xxx/prog1.py
:    ~/project/dev/xxx/prog2.py

: And:

:    ~/project/live/yyy/prog1.py
:    ~/project/live/yyy/prog2.py
:    

: (The reason for this is that I have separate development and live 
: versions of the project, and the development version of prog1 wants
: to run the development version of prog2, and the live version of
: prog1 wants to run the live version of prog2).

: prog2.py typically contains constants for the progject, e.g:

:    nntpServer = "news.demon.co.uk"

: etc. The constants will typically be different on the live and
: development versions.

Unless you've changed the path, the directory of the script should be
the first item in sys.path; this means that importing "prog2" should take
it from the same set of files as the script.  So...
  dev/xxx/prog1.py would import dev/xxx/prog2.py
  live/yyy/prog1.py would import live/yyy/prog2.py

You might want to print the path when you run the script to see, also
print the __file__ attribute of the imported module:

  import sys, prog2
  print 'The import path is', sys.path
  print sys.__name__, 'imported from', sys.__file__
  print prog2.__name__, 'imported from', prog2.__file__

This should help you debug the script (especially if it is a CGI
script).

  -Arcege





More information about the Python-list mailing list