import from environment path

Chris Torek nospam at torek.net
Sat Jun 18 20:56:28 EDT 2011


In article <3a2b0261-ee10-40c0-8fad-342f186eea60 at q30g2000yqb.googlegroups.com>
Guillaume Martel-Genest  <guillaumemg at gmail.com> wrote:
>Here's my situation : I got a script a.py that need to call b.py. The
>2 scripts can't be in a same package. Script a.py knows the path of
>b.py relative to an environment variable B_PATH, let's say B_PATH/foo/
>b.py. The solution I found is to do the flowwing :
>
>b_dir = os.path.join(os.environ['B_PATH'], 'foo')
>sys.path.append(b_dir)
>import b
>b.main()
>
>Is it the right way to do it, should I use subprocess.call instead?

The "right" way depends on what you want to happen.

Consider, e.g., the case where sys.path starts with:

    ['/some/where/here', '/some/where/there', ...]

and program a.py lives in /some/where/here.  Suppose B_PATH is
'/where/b/is'.  The sys.path.append will leave sys.path set to:

    ['/some/where/here', '/some/where/there', ..., '/where/b/is']

If /some/where/there happens to contain a b.py, your "import b"
will load /some/where/there/b.py rather than /where/b/is/b.py.

Did you want that?  Well, then, good!  If not ... bad! :-)

Consider what happens if there is a bug in b.main(), or b.main()
is missing entirely.  Then "import b" works, but the call b.main()
raises an exception directly in program a.py.

Did you want that?  Well, then, good!  If not ... bad! :-)

You might also want to take a look at PEP 302:

    http://www.python.org/dev/peps/pep-0302/

If you use "subprocess" to run program B, it cannot affect program
A in any way that program A does not allow.  This gives you a lot
more control, with the price you pay being that you need to open
some kind of communications channel between the two programs if
you want more than the simplest kinds of data transfer.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list