How to read set environment variable in python [duplicate] - python

This question already has answers here:
Reading and writing environment variables in Python? [duplicate]
(4 answers)
Closed 7 years ago.
In UNIX from command line, I do
setenv HOME <path to home>
I pass it as argument to my python script
python hello.py HOME
and do
sys.argv[1] = os.environ["HOME"]
still it doesn't read the path.
I am new to python, is os.environ correct for this case?

If your aim is to get the path of the home directory as argument, you can just make your user send it by making shell evaluate the argument before calling the script.
I have a simple script like -
import sys
print(sys.argv[1])
In Windows I call it as -
set HOME=D:\
python script.py %HOME%
The output I get is -
D:\
In Linux -
$ python hello.py $HOME
output -
/home/random/
If you want to get it from the environment variable, and you want to pass the environment variable to use as the first argument to the script, then you should change your script like -
sys.argv[1] = os.environ.get(sys.argv[1],sys.argv[1])
This would

It seems this depends a little on your shell. For example, in Linux using bash 4.3-7ubuntu1.5:
$ export XXX="abc"
$ python
>>> import os
>>> os.environ["XXX"]
'abc'
>>> os.environ["HOME"]
'/home/alan'

Related

How to set python scripts launch locations in windows 10

I thought it will be as simple as adding these locations to Path or PYTHONPATH. I added them to PYTHONPATH and added PYTHONPATH to Path.
When running SET of window's terminal I can see my newly set paths;
E:\Tests> SET
Path=E:\Tests\PythonTests
PYTHONPATH=E:\Tests\PythonTests
(I simplified the list for readability)
I then create a very simple python file test.py inside E:\Tests\PythonTests with a single line:
print ("Hello world")
Now, if I cd \Tests\PythonTests I can run it successfully:
E:\Tests\PythonTests> python test.py
Hello world
If I cd \Tests I can:
E:\Tests> python pythonTests/test.py
Hello world
But if I try
E:\Tests> python test.py
python: can't open file 'test.py': [error 2] No such file or directory
Python version:
E:\Tests\PythonTests>python --version
Python 3.8.0
Am I'm missing something? What am I doing wrong?
The PYTHONPATH env var does not control where the python command searches for arbitrary Python programs. It controls where modules/packages are searched for. Google "pythonpath environment variable" for many explanations what the env var does. This is from python --help:
PYTHONPATH : ':'-separated list of directories prefixed to the
default module search path. The result is sys.path.
Specifying a file from which to read the initial Python script is not subject to any env var manipulation. In other words, running python my_prog.py only looks in the CWD for my_prog.py. It does not look at any other directory.

Run python file from bash, send parameter from bash to py and output the result by echo on bash [duplicate]

This question already has answers here:
How to pass a Bash variable to Python?
(4 answers)
How do I set a variable to the output of a command in Bash?
(15 answers)
Command not found error in Bash variable assignment
(5 answers)
Closed 2 years ago.
The question is related to Linux Debian, bash and python3.
Run python3 file from bash, send parameter from bash to py and output the result by echo on bash.
The follow are a sample which works for me. This one start a python3 script by bash and get the outpup of python3 script on terminal.
bash_script.sh
#!/bin/bash
python3 python_script.py
python_script.py
#!/usr/bin/env python3
import random # import the random module
# determining the values of the parameters
mu = 100
sigma = 25
print(random.normalvariate(mu, sigma))
Whats my question:
How to change the code, for send the parameter for "mu" and "sigma" from bash to python and output the python result on bash by "echo $python_script_output" ?
Follow the not working draft for a solution:
bash_script.sh
#!/bin/bash
mu = 100
sigma = 25
python3 python_script.py
echo $python_script_output
python_script.py
#!/usr/bin/env python3
import random
print(random.normalvariate(mu, sigma))
Is there a particular reason you are looking to run the python script via bash?
If not, you can use in-built python module sys to pass arguments to the python script and print results directly on terminal.
import sys
def func(arg1, arg2):
# do_somehing
arg1, arg2 = sys.argv[1], sys.argv[2]
print(func(arg1, arg2))
Then you can use it directly from bash
python script_name.py arg1 arg1

Replicate ". ./bash.sh" shell command in python script [duplicate]

I want to implement a userland command that will take one of its arguments (path) and change the directory to that dir. After the program completion I would like the shell to be in that directory. So I want to implement cd command, but with external program.
Can it be done in a python script or I have to write bash wrapper?
Example:
tdi#bayes:/home/$>python cd.py tdi
tdi#bayes:/home/tdi$>
Others have pointed out that you can't change the working directory of a parent from a child.
But there is a way you can achieve your goal -- if you cd from a shell function, it can change the working dir. Add this to your ~/.bashrc:
go() {
cd "$(python /path/to/cd.py "$1")"
}
Your script should print the path to the directory that you want to change to. For example, this could be your cd.py:
#!/usr/bin/python
import sys, os.path
if sys.argv[1] == 'tdi': print(os.path.expanduser('~/long/tedious/path/to/tdi'))
elif sys.argv[1] == 'xyz': print(os.path.expanduser('~/long/tedious/path/to/xyz'))
Then you can do:
tdi#bayes:/home/$> go tdi
tdi#bayes:/home/tdi$> go tdi
That is not going to be possible.
Your script runs in a sub-shell spawned by the parent shell where the command was issued.
Any cding done in the sub-shell does not affect the parent shell.
cd is exclusively(?) implemented as a shell internal command, because any external program cannot change parent shell's CWD.
As codaddict writes, what happens in your sub-shell does not affect the parent shell. However, if your goal is to present the user with a shell in a different directory, you could always have Python use os.chdir to change the sub-shell's working directory and then launch a new shell from Python. This will not change the working directory of the original shell, but will leave the user with one in a different directory.
As explained by mrdiskodave
in Equivalent of shell 'cd' command to change the working directory?
there is a hack to achieve the desired behavior in pure Python.
I made some modifications to the answer from mrdiskodave to make it work in Python 3:
The pipes.quote() function has moved to shlex.quote().
To mitigate the issue of user input during execution, you can delete any previous user input with the backspace character "\x08".
So my adaption looks like the following:
import fcntl
import shlex
import termios
from pathlib import Path
def change_directory(path: Path):
quoted_path = shlex.quote(str(path))
# Remove up to 32 characters entered by the user.
backspace = "\x08" * 32
cmd = f"{backspace}cd {quoted_path}\n"
for c in cmd:
fcntl.ioctl(1, termios.TIOCSTI, c)
I shall try to show how to set a Bash terminal's working directory to whatever path a Python program wants in a fairly easy way.
Only Bash can set its working directory, so routines are needed for Python and Bash. The Python program has a routine defined as:
fob=open(somefile,"w")
fob.write(dd)
fob.close()
"Somefile" could for convenience be a RAM disk file. Bash "mount" would show tmpfs mounted somewhere like "/run/user/1000", so somefile might be "/run/user/1000/pythonwkdir". "dd" is the full directory path name desired.
The Bash file would look like:
#!/bin/bash
#pysync ---Command ". pysync" will set bash dir to what Python recorded
cd `cat /run/user/1000/pythonwkdr`

Python 3.8.1 win 10 cmd sys args issue [duplicate]

This question already has an answer here:
Python Script does not take sys.argv in Windows
(1 answer)
Closed 2 years ago.
Does anyone know why I can't send arguments when executing a script?
I have installed python 3.8.1, Windows 10 x64. I have an environment variable (the folder where my scripts are). I can execute the scripts like this:
nameScript.py
and it works but if I put
nameScript.py 1
and in this script I use that '1', sys.argv[1] give an error: Index out of bounds.
If I execute the script like:
python D/path_to_script/nameScript.py 1
it works.
your editor configuration is different than default command prompt.May be that is not reading your path and other things.
when executing like
nameScript.py 1
it understand that nameScript.py is a program and 1 is argument.
hence
sys.argv[0] = 1
sys.argv[1] = Error
sys.argv is filled with command line arguments. The first one sys.argv[0] is the script name, then sys.argv[1] is the first argument. Like this:
python myscript.py arg1 arg2
Then sys.argv[0] is 'myscript.py' sys.argv[1] is 'arg1' sys.argv[2] is 'arg2'
I think you need to create an enviroment variable that points to your python/bin folder instead your project/script folder.

Export a variable from bash and use it in Python

I am trying to write a script which is executing couple of things on a Linux server and I would like to use bash for most of the Linux specific commands and only use Python for the most complex stuff, but in order to do that I will need to export some variables from the bash script and use them in the python script and I didn't find a way how I can do that. So I have tried to create two very little scripts to test this functionality:
1.sh is a bash script
#!/bin/bash
test_var="Test Variable"
export test_var
echo "1.sh has been executed"
python 2.sh
2.sh is a Python script:
#!/usr/bin/env python3
print("The python script has been invoked successfully")
print(test_var)
As you can guess when I execute the first script the second fails with the error about unknown variable:
$ ./1.sh
1.sh has been executed
The python script has been invoked successfully
Traceback (most recent call last):
File "2.sh", line 4, in <module>
print(test_var)
NameError: name 'test_var' is not defined
The reason why I am trying to do that is because I am more comfortable with bash and I want to use $1, $2 variables in bash. Is this also possible in Python?
[EDIT] - I have just found out how I can use $1 and $2 it in Python. You need to use sys.argv[1] and sys.argv[2] and import the sys module import sys
To use environment variables from your python script you need to call:
import os
os.environ['test_var']
os.environ is a dictionary with all the environment variables, you can use all the method a dict has. For instance, you could write :
os.environ.get('test_var', 'default_value')
Check python extension it should be .py instead of .sh
1.sh
#!/bin/bash
test_var="Test Variable"
export test_var
echo "1.sh has been executed"
python 2.py
os library will gave you the access the environment variable. Following python code will gave you the required result,
#!/usr/bin/env python3
import os
print("The python script has been invoked successfully")
print(os.environ['test_var'])
Check for reference : How do I access environment variables from Python?

Categories