Pass Python Variable to Shell [duplicate] - python

This question already has answers here:
Environment variables set from python not visible in shell script
(2 answers)
Closed 7 months ago.
I defined a shell script with a python script inside on the fly. Getting variables from shell to Python works fine, but the other way round does not work as expected. My Idea was to create an env variable os.environ["NEW_VAR"] = "test", but when trying is echo it, it is just None.
#!/bin/bash
args=("$#")
GIT_PASSWORD=${args[0]}
export GIT_PASSWORD=$GIT_PASSWORD
python - << EOF
import os
print(os.environ.get("GIT_PASSWORD"))
os.environ["NEW_VAR"] = "test"
EOF
echo $GIT_PASSWORD
echo $NEW_VAR
echo "Back to bash"
Why does that not work and 2. What is the correct way to pass a variable here?
Thank you!

Written in the comments, inheriting environment variables only works from parent to child processes, not the other way round.
if you need shell variables set from a python script you can create the output in your shell script and eval the results:
eval "$(python -c 'print("HELLO=WORLD")')"
echo "$HELLO"
yields WORLD

Related

How python can execute shell command with env [duplicate]

This question already has answers here:
Why can't I specify an environment variable and echo it in the same command line?
(9 answers)
Python subprocess/Popen with a modified environment
(9 answers)
Closed 3 months ago.
Basically, os.system() can execute shall commands, such as:
os.system("echo $A")
It will work well and output value environment variable A.
But this seems to not work:
os.system("A=b echo $A")
It won't output "b" as expected.
How Python can execute this type of command command?
It won't output "b" as expected.
The expansion $A to empty string is done by the shell earlier, before running echo.
Try this:
os.system("A=b; echo $A")

How do i set environment variable using python script [duplicate]

This question already has answers here:
set environment variable in python script
(3 answers)
Set shell environment variable via python script
(4 answers)
Closed 4 years ago.
I tried both
os.environ['TemporaryVar'] = "Apple"
and
os.putenv("TemporaryVar", "Apple")
but after running the python script, when i run the command env or set in the command line, i do not see variable as
TemporaryVar=Apple
I also have a sleep(50) in the python script so that the script does not terminate while i am checking for set or env in command line.
What i want is to write a python script that adds a variable to the environment variable. (I should be able to see it when i type env)
This is not possible.
Environment variables are defined in the scope of the job that sets it. That's why when you define an environment variable in one terminal session ,you won't see it in other sessions. The same thing is happening with your script. A job runs your python script but you are trying to read variables from another terminal session(another job), so you can't see them. Depending on your goal, you have to find a workaround.

make #!/usr/bin/env python -u shebang portable [duplicate]

This question already has answers here:
Cannot pass an argument to python with "#!/usr/bin/env python"
(9 answers)
Closed 9 years ago.
I have this non-portable shebang:
#!/usr/bin/env python -u
It is non portable because python -u is fed as one single arg to env on my system.
Challenge: make this shebang portable changing the shebang only - that is to say a one-liner.
In other words, no solutions
from the question Disable output buffering
from the question Cannot pass an argument to python with "#!/usr/bin/env python"
I'd use the following:
#!/bin/sh
"""true"
exec python -u "$0" "$#"
"""
# python code goes here
The line """true" will be parsed by sh as true, because it consists of an empty "" string followed by "true". Since true is a no-op command, it will be effectively ignored, and the following line will execute the Python interpreter.
On the other hand, Python will parse the """true" line very differently, as the opening of a triple-quoted string which starts with true" and is closed two lines below. Since the string is not used for anything, the Python interpreter will effectively ignore the shell snippet that starts up Python. It is the difference in interpretation of """xxx" that allows Python and sh code coexist in the same script.
For a simple test, append something like:
import sys
print "hello!", sys.argv
Given a reasonable sh implementation (and taking into account the time to start Python), this should not be measurably slower than using env.

How to create tcsh aliases using python?

I am trying to created aliases for tcsh from a python script (running Python 2.7.1).
Once the aliases are created I want to use them in the same shell I ran the python script in.
I tried:
os.system('alias test "echo test"')
but I get the following error:
sh: line 0: alias: test: not found
sh: line 0: alias: echo test: not found
I then tried:
os.system(r"""/bin/csh -i -c 'alias test "echo test"'""")
And then no errors occurred, but the alias did not register, and therefore I could not use it.
The result I'm looking for is this:
tcsh>python my_script.py
tcsh>test
test
Thanks!
os.system executes that command in a subshell (the bourne shell by the look of it), so even if your syntax was correct alias test="echo test", it would not persist after the call (since the subshell closed).
But this seems like an XY question. You ask about Y - the solution you had in mind, and not about X - your problem.
If you simply want to create a bunch of aliases at once, why not use a c-shell script!? (Why you are torturing yourself with c-shell is another matter entirely).
Your python script cannot execute anything in the context of your shell. While you could use subprocess.call(..., shell=True) this would use a new shell and thus not update your existing shell.
The only way to do what you want is to make your python script write valid shell commands to stdout and then, instead of just executing it, you need to make your shell evaluate the output of your python script.

Stop Python from generating pyc files in shebang [duplicate]

This question already has answers here:
How to avoid .pyc files?
(10 answers)
Closed 9 years ago.
Is there a way to stop python from creating .pyc files, already in the shebang (or magic number if you will) of the Python script?
Not working:
#!/usr/bin/env python -B
it is possible by putting your python interperter path directly in the she bang instead of using env.
#!/usr/bin/python -B
of course this means you lose out on some of the portability benefits of using env. There is a discussion of this issue with env on the wikipedia Shebang page. They use python as one of their env examples.
According to the man page for env, you can pass name=value to set environment variables. The PYTHONDONTWRITEBYTECODE environment variable causes Python to not write .py[co] files (the same as the -B flag to python). So using
#!/usr/bin/env PYTHONDONTWRITEBYTECODE=1 python
should do the trick.
EDIT:
I tested this with a simple Python script:
#!/usr/bin/env PYTHONDONTWRITEBYTECODE=1 python
print 1
then
$chmod +x test.py
$./test.py
1
$ls
test.py
(but not test.pyc)
Yes, if and only if, we assume the Python program runs in a somewhat POSIX compatible system (for /bin/sh), this will work:
(IMPROVED based on input from glglgl)
#!/bin/sh
"exec" "python" "-B" "$0" "$#"
# The rest of the Python program follows below:
Alas, no. The shebang stuff is limited to giving an executable and one parameter.
So env tries to execute python -B with the given file as one argument instead of python with -B and the current file as two arguments.
I don't see a way to achieve the wanted goal.

Categories