1

I'm using OS X 10.8.3.

If you open a terminal,

echo $PATH

/usr/local/bin is there, also if you run it via sh or bash

however the python code output of:

import os
print os.environ.copy()

lacks the /usr/local/bin path

Can anyone explain how $PATH works? is there something that extends it? why did the python script didn't print the $PATH I see in the terminal? Does it behave the same on linux distributions?

How did I encountered it? I installed a sublime 2 plugin, js2coffee, the plugin runs a subprocess (import subprocess), providing the name of an exec, js2coffee - which was in the /usr/local/bin, a path that wasn't in the python os env. In order to fix it I had to add it to the env:

env = os.environ.copy()
env["PATH"] = "/usr/local/bin/"

js2coffee = subprocess.Popen(
    'js2coffee',
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True,
    env= env
)
4

1 回答 1

3

Terminal windows host interactive shells, typically bash. Shells get initialized using a variety of profile and "rc" files, as documented in their man pages (e.g. bash). That initialization will change the environment in myriad ways.

In particular, /etc/profile runs the path_helper tool to add directories to the PATH variable.

Applications launched from the Finder, Dock, Launchpad, etc. do not run shells and don't have similar environments. They inherit a fairly basic environment from their parent process, ultimately going back to launchd. See, for example, the output of launchctl export. You could also use Automator, AppleScript Editor, or the third-party tool Platypus to run the env command from a GUI app to see what it has.

I'm not certain about what is standard for Linux shells, but the same principal applies. Programs launched from your desktop environment will inherit the environment directly. Shells will initialize their environment using various script files and may therefore have different environments.

于 2013-03-30T11:03:14.123 回答