Importing creating an environment variable in Python? - python

This could be a silly question. I have code that calls a subprocess in Python. For it to work and find the program I will need to set an environment variable on my Mac TEST__LIB_PATH.
subprocess.call(["find_info",
image,
json_file])
Is there a way in Python I can just import this environment variable to use instead of having to set this up globally?

call takes a keyword argument env that takes a mapping to use as the environment for the command. The current environment is in os.environ; you can extend that with something like
subprocess.call(["find_info", image, json_file],
env=dict(TEST__LIB_PATH="/path/requried/for/test",
**os.environ))

You can access environment variables with os.environ:
import os
print(os.environ['TEST__LIB_PATH'])
os.environ also has a get() method:
os.environ.get('TEST__LIB_PATH')
Edit: here's a link to the docs

Related

How do I add a directory to system environment variable using python script [duplicate]

From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system?
The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms.
My test code is
import os
os.environ['FAKE'] = 'C:\\'
Opening another instance of Python and requesting os.environ['FAKE'] yields a KeyError.
NOTE: Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary.
That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.
You can using SETX at the command-line.
By default these actions go on the USER env vars.
To set and modify SYSTEM vars use the /M flag
import os
env_var = "BUILD_NUMBER"
env_val = "3.1.3.3.7"
os.system("SETX {0} {1} /M".format(env_var,env_val))
make them stick by committing them to
the system?
I think you are a bit confused here. There is no 'system' environment. Each process has their own environment as part its memory. A process can only change its own environment. A process can set the initial environment for processes it creates.
If you really do think you need to set environment variables for the system you will need to look at changing them in the location they get initially loaded from like the registry on windows or your shell configuration file on Linux.
Under Windows it's possible for you to make changes to environment variables persistent via the registry with this recipe, though it seems like overkill.
To echo Brian's question, what are you trying to accomplish? There is probably an easier way.
Seems like there is simplier solution for Windows
import subprocess
subprocess.call(['setx', 'Hello', 'World!'], shell=True)
I don't believe you can do this; there are two work-arounds I can think of.
The os.putenv function sets the environment for processes you start with, i.e. os.system, popen, etc. Depending on what you're trying to do, perhaps you could have one master Python instance that sets the variable, and then spawns new instances.
You could run a shell script or batch file to set it for you, but that becomes much less portable. See this article:
http://code.activestate.com/recipes/159462/
Think about it this way.
You're not setting shell environment variables.
You're spawning a subshell with some given environment variable settings; this subshell runs your application with the modified environment.
According to this discussion, you cannot do it. What are you trying to accomplish?
You are forking a new process and cannot change the environment of the parent process as you cannot do if you start a new shell process from the shell
You might want to try Python Win32 Extensions, developed by Mark Hammond, which is included in the ActivePython (or can be installed separately). You can learn how to perform many Windows related tasks in Hammond's and Robinson's book.
Using PyWin32 to access windows COM objects, a Python program can use the Environment Property (a collection of environment variables) of the WScript.Shell object.
Try to use py-setenv that will allow you to set variable via registry
python -m pip install py-setenv
From within Python? No, it can't be done!
If you are not bound to Python, you should consider using shell scripts (sh, bash, etc). The "source" command allows you to run a script that modifies the environment and will "stick" like you want to the shell you "sourced" the script in. What's going on here is that the shell executes the script directly rather creating a sub-process to execute the script.
This will be quite portable - you can use cygwin on windows to do this.
In case someone might need this info. I realize this was asked 7 yrs ago, but even I forget how sometimes. .
Yes there is a way to make them "stick" in windows. Simply go control panel, system, advanced system settings,when the system properties window opens you should see an option (button) for Environment Variables. .The process for getting to this is a little different depending on what OS you're using (google it).
Choose that (click button), then the Environment Variables window will open. It has 2 split windows, the top one should be your "User Variables For yourusername". . .choose "new", then simply set the variable. For instance one of mine is "Database_Password = mypassword".
Then in your app you can access them like this: import os, os.environ.get('Database_Password'). You can do something like pass = os.environ.get('Database_Password').

How to get all jenkins variables

I want to write a python script to get list of "jenkins" variables and show them.
I wrote this, but it returned all environment variables instead of jenkins variables.
import os
print os.environ
How can I get them in python script?
Jenkins variables are environment variables. There isn't really anything that separates them.
You can use EnvInject plugin to clean the Jenkins environment of all OS environment variables that are inherited, this way you are left with "just Jenkins environment variables", but careful as this may break your tools as none of the paths will be set.
If you want to view just the Build Parameters, you can use the Jenkins API for each job, or parse the job's XML file
There is a specific set of built-in variable that a base Jenkins install adds to each execution step; here is a list from the reference:
https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-below
As Slav says, these are just like any other environment variable, and if you want to access one you would just ask for it by name e.g., for $WORKSPACE, you would use os.environ['WORKSPACE']
You could enumerate the variables at the url above in a list ['WORKSPACE', ...] and print them that way...

Trying to get an enviroment variable in python, not working

Say I do this in the terminal
TEST="abc"
A python script run after this (same session, variable is definitely still there) raises a KeyError as the key TEST doesn't exist. How do I access this environment variable?
import os
print os.environ["TEST"]
# bash
export TEST=abc
# sh
TEST=abc
export TEST
Make sure to export the variable. By default environment variables are not inherited by child processes. Marking them as exported tells the shell to pass them to its children.
In the terminal, do
export TEST="abc"

Add an environment variable using Python

I'm trying to add an environment variable to my windows machine using python and the code is something like:
import os
os.environ["TONY"] = "C:\\"
or
import os
os.putenv["TONY", "C:\\"]
But I dont see the entry in the system environment variables. Is the because the list of variables when you type 'set' in cmd is read from the machines registry?
Is there a way to add a variable on windows so it shows up in system variables?
Short answer: Python cannot edit environment variables in a way that sticks. BUT, if all you want to do is run something in a temporarily modified environment, you can do that with the subprocess module:
import os
from subprocess import Popen
myEnv = dict(os.environ)
myEnv['newKey'] = 'newVal'
shellCmd = Popen(['sh', 'someScript.sh'], env=myEnv)
(shellOut, shellErr) = shellCmd.communicate()
If you're getting an error because the program you're running is not defined in the Windows Environment path and you don't want to ask the user to do that manually then a workaround is to specify the full location of the exe file such as in this example in the picture

Is there a commandline flag to set PYTHONHOME?

I'm attempting to run python on a system that doesn't allow me to set environment variables. Is there a commandline flag to python that will set PYTHONHOME? I looked here: http://docs.python.org/release/2.3.5/inst/search-path.html but didn't see anything.
So, hopefully something like this:
python -magical_path_flag /my/python/install test.py
EDIT
Thanks for the responses everyone. I'm embarrassed to say I actually meant PYTHONHOME, not PYTHONPATH. (That's what I deserve for asking a question at 1:30 AM.) I've edited my quesiton.
Here's some more info. I'm trying to get python running on Android. I can run python -V no problem, but if I try and execute a script, I get:
I/ControlActivity(18340): Could not find platform independent libraries <prefix>
I/ControlActivity(18340): Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Unfortunately when using the ProcessBuilder and changing the environment variables on Android, it says that they're not modifiable and throws an exception. I'm able to pass all the command line flags I want, so I was hoping I could set PYTHONHOME that way.
I've tried creating a wrapping shell script which exports PYTHONHOME and then calls python but that didn't work. (Got the same error as before.)
Thanks,
Gabe
You could simply set it in your script -- sys.path is a regular, modifiable list. Something like:
import sys
sys.path.append("/path/to/libraries")
should do the trick
In UNIXy shells, you can set an environment variable just for the duration of one command by prepending the command with the environment variable setting:
$ PYTHONPATH=/my/python/install python test.py
If none of the other answers suit you, you can write a wrapper script that temporarily sets the environment variable then exec's your other script. For example:
python mywrapper.py -magical_path_flag /my/python/install test.py

Categories

Resources