In every operating system, the environment variable PATH plays a crucial role. It is a set of directories where executable programs are located. In Python, however, there might be situations where you need to set or modify the PATH directly from a script. This tutorial walks you through how to do exactly that.
Step 1: Import Required Libraries
The first step is to import the os module; a standard Python library that provides functions for interacting with the operating system, including the environment variables.
1 |
import os |
Step 2: Access the Current PATH
The current PATH can be accessed using the os.environ function from the os library.
1 |
print(os.environ['PATH']) |
The output (might vary) should look similar to the following:
/usr/local/bin:/usr/bin:/usr/sbin:/sbin
Step 3: Modify the PATH
To modify PATH, we append or prepend the new directory path to the existing PATH string. Remember that multiple paths are separated by a colon (:).
Let’s try adding “/path/to/my/directory” to the existing PATH:
1 2 3 |
import os os.environ['PATH'] = '/path/to/my/directory:' + os.environ['PATH'] print(os.environ['PATH']) |
Step 4: Validate the Change
You can verify the change by printing the PATH again.
1 |
print(os.environ['PATH']) |
If everything works correctly, the output should start with “/path/to/my/directory”, followed by the previous PATH.
Full Code
Here’s the complete code that includes all the steps discussed above:
1 2 3 4 5 6 7 8 9 10 |
import os # print the current PATH print(os.environ['PATH']) # append / prepend to PATH os.environ['PATH'] = '/path/to/my/directory:' + os.environ['PATH'] # validate changes print(os.environ['PATH']) |
Conclusion
Thank you for going through this tutorial; now you should be able to set the PATH variable in a Python script. Remember, manipulating system-level environment variables can impact other applications or scripts, so use this with caution. For temporary changes, consider using only within the context where the change is needed.