Accessing /etc/environment value in unix using python error? - python

I tried to set a new "System wide environment" variable and tried to access it using python. I put 'PRODUCTION_SERVER'=1 in etc/environment. After rebooting i tested it in python interpreter and it was successful
>>> import os
>>> os.environ.get('PRODUCTION_SERVER')
'1'
>>>
But when i used the same line inside my flask project in that server it returned None.
import os
print os.environ.get('PRODUCTION_SERVER')
Output
None
Why am i getting different results in same system?

Don't know if this is the problem, but:
The /etc/environment file is only loaded when you log in (it is read by the pam_env PAM module). If your flask service is running an an environment that was created before you changed the /etc/environment file, it would not see new values you have entered into that file.

Related

Access environment variable in macOS from python

I had no .bash_profile file so I created one and the only line in it is this:
YOUTUBE_API=someRandomString
In my .zshrc file the first line is this:
source ~/.bash_profile
And from the command line I can run this:
echo $YOUTUBE_API
Which gives me a correct output (my API key).
But when I try to do it in Python it returns None:
import os
print(os.environ.get('YOUTUBE_API'))
I'm running python version 3.9.4. Any idea why, and how I may fix it?
Thank you
You need
export YOUTUBE_API=someRandomString
Otherwise, the variable is available to the local shell, but not to any subprocesses.
It only depends on where you run your code from:
if the process the code runs in has the variable set, it shouldn't be None
if you run the code inside another process, you'll get None
Explanation:
Each process ID gets it's own environment, stored in /proc/<pid>/environ file, where its local non-exported variables get stored. this path gets deleted as soon as the process stops.
The only way to make this work is to either export the variable in the shell, before launch the program, or run YOUTUBE_API=someRandomString python <your python file>

Python does not see env variables set from Jenkins Parameterized build

I am trying to retrieve the parameters set from the jenkins build into my python script, but am having trouble. I understand the parameters set from here:
Are set as env variables and all I have to do in python is do:
# Env variables
UPDATE_DATA = os.environ.get('update_data')
ALL_BUILDS = os.environ.get('all_builds')
However I am getting None for those values. When I do an echo of those parameters in my jenkins script before my python script runs, I could see them being printed out correctly. However, for some reason python does not see them. If I go manually into a terminal and export a variable and run my python script, it works.. So I'm completely lost here.
Jenkins server is running on linux. Using python 2.7
You can use the boolean variable like this:
Output:
It seems like when I ran the python script in the Jenkins config (not inside a file within my project) like how #souravatta suggested, it found the env variable. So that means the env variable Jenkins is setting, is on a different instance somehow (even though they are on the same computer, same user). I just did a workaround where I wrote the env variables to a file and then just read that file in my python script.

Launching script to export environment variables from Python

I'm trying to remove all passwords and secrets from applications.
To do this, I'm using environment variables. I would like to avoid putting this specific stuff into ~/.bashrc or other built in files. It would be ideal to call a specific script that exports the desired variables.
The reason for this is because the environment variables contain passwords and I'm trying to isolate them outside of all code except the environment scripts that set environment variables.
To summarize the desired flow:
Launch Python app
App spawns process that sets new environment variables
App pulls values from previously set environment variables
App uses those values in further processing
contents of testpy.py
#!/usr/bin/env python
import os
import subprocess
env_file='/tmp/env_file'
db_pass_var='DBPASS'
#execute bash script that sets the env vars
subprocess.call([".", env_file], shell=True)
#try to get the variable set and print it
print os.getenv(db_pass, 'fail')
contents of /tmp/env_file
#!/usr/bin/env bash
export DBUSER="myuser"
export DBPASS="mypass"
I've tried various methods like subprocess.Popen commands I found on other stackoverflow threads but nothing seems to work.
Alternatives that I want to avoid:
Running the env_file script first, then launching the python code. The goal is to run it all from 1 application.
Putting the passwords into a config file. The goal is environment variables. Config files I would like to reserve to pointing to what variable to call, rather than setting the env vars themselves. This is because config files are checked into source control. The only thing I want to leave out of source control is the actual export environment variables themselves which contain all sensitive environment info.
There's an easier way. Just provide a wrapper script that sets the environment variables and then calls your main script.
It's convenient to use the envdir utility for this. If you can't use that for some reason, then set env vars directly using os.environ and spawn off your main script as a child process.

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

python change starting up/default directory

I am new to python.
Every time I start the shell, it always gives me directory as:
".../file name/Python/"
But I want to change it to:
".../file name/python program/"
How do I do it without changing the import modulate stuff?
I am afraid to make it wrong so that I can't import anymore, but it is so annoy to put:
import os
os.chdir(".../file name/python program/")
every time after I open the shell.
Thanks for help!
Checkout: http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP
This is an environment variable that can be set to a file. This is executed prior to start up of shell and only applies if you are using interactive shell.
You can use this to specify a path as current directory at start of your shell.
import os
os.chdir('/pathto')
del os
Write to a file and point to it with env variable.
If this is just specific to a file that you are running, then you should be changing the directory inside the script
os.chdir('/pathto')
If you are trying to set up python so that it will automatically search in a specific directory on your computer when you import modules, open to your /python27/Lib/site.py file and add your paths to the PREFIXES list near the top of the file

Categories

Resources