2

I know that I can get and modify the PATH variable by doing something like os.environ["PATH"] += "path/to/dir".

But is there any way to ensure that the new path gets written to the beginning of PATH?

3
  • 1
    yes you can do it the same way you would manipulate strings however, why would you ever do this in Python? this screams of bad practice Commented Apr 14, 2020 at 16:55
  • 1
    Yes. Just add the path this way: os.environ['PATH'] = "path/to/dir" + os.environ['PATH'] Commented Apr 14, 2020 at 16:55
  • I'm trying to set a directory containing a symlink to a conda-python-interpreter on the PATH-variable at runtime Commented Apr 15, 2020 at 10:15

1 Answer 1

3

os.environ["PATH"] = "path/to/dir" + os.pathsep + os.getenv("PATH")

https://docs.python.org/3/library/os.html

os.pathsep

The character conventionally used by the operating system to separate search path components (as in PATH), such as ':' for POSIX or ';' for Windows. Also available via os.path.

os.getenv(key, default=None)

Return the value of the environment variable key if it exists, or default if it doesn’t. key, default and the result are str.

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

1 Comment

add some explanation for what each os calls does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.