0

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!

7
  • 1
    os.system()? Not good... Commented Apr 25, 2013 at 15:18
  • Ouch. Is there a better style? I'm open to suggestion. Commented Apr 25, 2013 at 15:19
  • 2
    @ephedyn See the last sentence of kindall's answer. Commented Apr 25, 2013 at 15:20
  • @Aya I don't see any answer from a kindall, did something happen? Btw your answer does exactly what I was trying to do - thanks! Commented Apr 25, 2013 at 15:31
  • 1
    Alas, kindall has deleted their answer - whyever. So the answer is "Use the subprocess module". Commented Apr 25, 2013 at 15:31

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for calling with full path, -0.4 for not recommending subprocess, makes +0.6, rounds to +1.
@glglgl I thought it'd be rude to usurp kindall's suggestion of subprocess, but now he's deleted it, I'll add it in.
1

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/

1 Comment

Thanks for the tips, will go through them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.