import from environment path

  • Thread starter Guillaume Martel-Genest
  • Start date
G

Guillaume Martel-Genest

Hi,

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?
 
C

Chris Torek

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top