Python capture environment variables

this bash script can catch all environment variables that are set when data is passed via STDIN, for example:

echo "Hello" | ./script.sh 

script.sh

 #!/bin/bash CAPTURE_FILE=/var/log/capture_data env >> ${CAPTURE_FILE} exit 1 

is it there somehow i can do the same in python ??

RESOLVED:

This is the resulting version of python.

 #!/usr/bin/env python import os import sys def capture(): log = os.environ data = open("/tmp/capture.log", "a") for key in log.keys(): data.write((key)) data.write(" : ") for n in log[key]: data.write('%s' % ((n))) data.write("\n") data.close() sys.exit(1) def main(): capture() if __name__ == "__main__": main() 
+4
source share
2 answers

Of course check os.environ .

 matan@swarm ~ $ python Python 2.7.2+ (default, Jan 20 2012, 17:51:10) [GCC 4.6.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print os.environ {'LOGNAME': 'matan', 'WINDOWID': '25165833', 'DM_CONTROL': '/var/run/xdmctl', 'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games', 'DISPLAY': ':0', 'SSH_AGENT_PID': '3648', 'LANG': 'en_GB.UTF-8', ... } 
+8
source

os.environ is a mapping containing all environment variables and their values.

+2
source

Source: https://habr.com/ru/post/1394373/


All Articles