简体   繁体   中英

Inheritance of env variables in python

I need to retrieve the env variable $PS1 of the parent process (the shell) that calls the python program. $PS1 doesn't belong to os.environ inside the python process and sys.ps1 stores its own prompt.

How can we pass this variable to the program from the shell ?

I invoke the program with : python3 program.py from the shell.

If value assigned to $PS1 doesn't change during runtime of your program.py then probably the best option is to pass it as an argument and retrieve it in you script using argparse . If the value is changing during runtime, then one of the options would be to store it in some temporary file and read it from there.

The python script can access all the environment variables through os.environ . Your problem is that PS1 is not an environment variable, but only a local variable of the shell.

That means that the shell does not pass it to its child in the environment (you can control that by typing env or printenv in your shell). So unless you manually put it in the environment before starting Python ( export PS1 for sh or bash) you cannot get it in your Python script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM