Skip to content Skip to sidebar Skip to footer

Set Bash Variable From Python Script

i'm calling a python script inside my bash script and I was wondering if there is a simple way to set my bash variables within my python script. Example: My bash script: #!/bin/bas

Solution 1:

No, when you execute python, you start a new process, and every process has access only to their own memory. Imagine what would happen if a process could influence another processes memory! Even for parent/child processes like this, this would be a huge security problem.

You can make python print() something and use that, though:

#!/usr/bin/env python3print('Hello!')

And in your shell script:

#!/usr/bin/env bash

someVar=$(python3 myscript.py)
echo"$someVar"

There are, of course, many others IPC techniques you could use, such as sockets, pipes, shared memory, etc... But without context, it's difficult to make a specific recommendation.

Solution 2:

shlex.quote() in Python 3, or pipes.quote() in Python 2, can be used to generate code which can be evaled by the calling shell. Thus, if the following script:

#!/usr/bin/env python3import sys, shlex
print('export foobar=%s' % (shlex.quote(sys.argv[1].upper())))

...is named setFoobar and invoked as:

eval"$(setFoobar argOne)"

...then the calling shell will have an environment variable set with the name foobar and the value argOne.

Post a Comment for "Set Bash Variable From Python Script"