elleciel
elleciel

Reputation: 2587

Setting path in Python

Is there a way to set the terminal path in Python? I have some compiled binaries that I'll like to use in a folder, let's just say foo.exe in C:/Program Files/PostgreSQL/9.2/bin, and I figured there had to be something in the os or sys modules that would work, but I couldn't find any:

# This works, but ugly
psqldir = 'C:/Program Files/PostgreSQL/9.2/bin'
currentdir = os.getcwd()
os.chdir(psqldir)
os.system('foo')
os.chdir(currentdir)

# Does not work
os.system('set PATH=%PATH%;C:/Program Files/PostgreSQL/9.2/bin')
os.system('foo')

# Does not work
sys.path.append('C:\\Program Files\\PostgreSQL\\9.2\\bin')
os.system('foo')

Thanks!

Upvotes: 0

Views: 245

Answers (2)

Aya
Aya

Reputation: 42080

Something like this should work...

import os

psqldir = 'C:/Program Files/PostgreSQL/9.2/bin'
os.environ['PATH'] = '%s;%s' % (os.environ['PATH'], psqldir)
os.system('foo')

...or just call foo.exe by its full path...

os.system('C:/Program Files/PostgreSQL/9.2/bin/foo')

However, as kindall's (now-deleted) answer suggested, it's worth noting this paragraph from the os.system() documentation...

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

Upvotes: 3

dusual
dusual

Reputation: 2217

How I understand this is that you need to add an environment variable . I think you should be able to do that using os.system / os.environ or subprocess . Also considering that you are on windows you might want to check these articles

http://code.activestate.com/recipes/416087/

http://code.activestate.com/recipes/159462/

Upvotes: 1

Related Questions