Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python capture environment variables

Tags:

python

linux

bash

this bash script can catch all the environment variables which are set when data is passed through STDIN eg such as:

echo "Hello" | ./script.sh

script.sh

#!/bin/bash

CAPTURE_FILE=/var/log/capture_data
env >> ${CAPTURE_FILE}
exit 1

it there any way i can do same in python??

RESOLVED:

this is the resultant python version..

#!/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()
like image 554
krisdigitx Avatar asked Feb 02 '12 11:02

krisdigitx


2 Answers

Sure, check out 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', ... }
like image 152
cha0site Avatar answered Sep 24 '22 22:09

cha0site


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

like image 21
Ignacio Vazquez-Abrams Avatar answered Sep 24 '22 22:09

Ignacio Vazquez-Abrams