Add an environment variable using Python - 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

Related

How to know where is windows installed with Python?

I am writing a program that needs to know which Drive is Windows drive . because I need to go to "Windows-Drive:\Users\publick\Desktop", I need some code or module that will give me the windows drive.
Thanks for your kindness.
If what you really want is the drive where Windows is installed, use
import os
windows_drive = os.environ['SystemDrive']
But it looks like what you actually need is the public desktop folder. You can get that easier and more reliably like this:
import os
desktop_folder = os.path.join(os.environ['PUBLIC'], 'Desktop')
For the current user's desktop folder instead, you can use this:
import os
desktop_folder = os.path.join(os.environ['USERPROFILE'], 'Desktop')
But I'm not sure that the desktop folder is always called 'Desktop' and that it's always a subdirectory of the profile folder.
There is a more reliable way using the pywin32 package (https://github.com/mhammond/pywin32), but it obviously only works if you install that package:
import win32comext.shell.shell as shell
public_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_PublicDesktop)
user_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_Desktop)
(Unfortunately pywin32 is not exactly well documented. It's mostly a matter of first figuring out how to do things using Microsoft's Win32 API, then figuring out where to find the function within pywin32.)
#!/usr/bin/env python3
# Python program to explain os.system() method
# importing os module
import os
# Command to execute
# Using Windows OS command
cmd = 'echo %WINDIR%'
# Using os.system() method
os.system(cmd) # check if returns the directory [var = os.system(cmd) print(var) ] in Linux it doesnt
# Using os.popen() method
return_value = os.popen(cmd).read()
can you check this approach ? I am not on Win
I found my Answer!
`import os
Windows-Drive=os.path.dirname(os.path.dirname(os.path.join(os.path.join(os.environ['USERPROFILE']))))
This code is answer!

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

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.

Importing creating an environment variable in 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

how to enter in to a folder through python code on linux

I am working on python(scrapy), i am trying to enter in to a folder by using os module but unable to do it, below is what i have tried
import os
scrapepath = "cd /home/local/username/project/scrapy/modulename"
os.system(scrapecmd)
Result:
0
Finally my intention is to enter in to a folder(Destination) from some where (for example home in linux) through python code as i mentioned above. Here actually i am generating some part of the path above dynamically and after that i should enter in to that path and run some commands from inside that folder
Can any one please let me know how to enter to a folder by using python code in linux as above.
To change the current working directory:
os.chdir("/home/local/username/project/scrapy/modulename")
You might also like to simply add that module to python's path (which is where import looks):
sys.path.append("/home/local/username/project/scrapy/modulename")
Use os.chdir:
import os
os.chdir("/home/local/username/project/scrapy/modulename")
AFAIK, os.system() executes the string command in a subshell. So, when you execute something like:
os.system("cd /path/to/directory/")
The cd command will actually be executed in a subshell. But, as the subshell exits after os.system execution, your cd has no practical effect for your application.
see http://docs.python.org/library/os.html
import os
os.chdir(path)

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