user2040074
user2040074

Reputation: 644

Set OS env var via python

Is there a way within Python to set an OS environment var that lives after the Python script has ended?.. So if I assign a var within the Python script and the script ends I want it to be available once I run a "printenv" via terminal. I've tried using the sh library using os.system but once the program finishes that var is not available via "printenv".

Upvotes: 1

Views: 339

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295472

You can do what ssh-agent, gpg-agent and similar tools do: Emit a shell script on your stdout, and document that the user should eval your program's output to activate the variables set by that script.

#!/usr/bin/env python
import shlex, pipes, sys

# pipes.quote on Python 2, shlex.quote on Python 3
quote = shlex.quote if hasattr(shlex, 'quote') else pipes.quote

# Detect when user **isn't** redirecting our output, and emit a warning to stderr
if sys.stdout.isatty():
    sys.stderr.write("WARNING: This program's output should be used as follows:\n")
    sys.stderr.write('           eval "$(yourprog)"\n')
    sys.stderr.write("         Otherwise environment variables will not be honored.\n")

new_vars={'foo': 'bar', 'baz': 'qux'}
for (k, v) in new_vars.items():
    sys.stdout.write('%s=%s; ' % (quote(k), quote(v)))
    sys.stdout.write('\n')

Use of quote() ensures that even a value like foo=$(run-something) is assigned as a literal value, rather than invoking run-something as a command.

Upvotes: 1

Fabien
Fabien

Reputation: 4972

You cannot do that. Child processes inherit environment of parent processes by default, but the opposite is not possible.

Indeed, after the child process has started, the memory of all other processes is protected from it (segregation of context execution). This means it cannot modify the state (memory) of another process.

At best it can send IPC signals...

More technical note: you need to debug a process (such as with gdb) in order to control its internal state. Debuggers use special kernel APIs to read and write memory or control execution of other processes.

Upvotes: 2

Related Questions