How Python reads environment variables and user-defined classes

Source: Internet
Author: User
This article mainly introduces how to read environment variables from Python and how to share custom classes. This article provides code examples directly. For more information, see Use OS. environ to read and modify environment variables:

The code is as follows:


Import OS

Print (OS. environ ["TEMP"])

Mydir = "c: \ mydir"
OS. environ ["MYDIR"] = mydir
Print (OS. environ ["MYDIR"])

PathV = OS. environ ["PATH"]
Print (pathV)
OS. environ ["PATH"] = mydir + ";" + OS. environ ["PATH"]
Print (OS. environ ["PATH"])

Custom python environment variable class:

The code is as follows:


Import OS

Class MyEnv:

Def _ init _ (self ):
Self. envFile = "c: \ myenv.txt"
Self. envs = {}

Def SetEnvFile (self, filename ):
Self. envFile = filename

Def Save (self ):
Outf = open (self. envFile, "w ")
If not outf:
Print ("env file cannot be opened for write! ")
For k, v in self. envs. items ():
Outf. write (k + "=" + v + "\ n ")
Outf. close ()

Def Load (self ):
Inf = open (self. envFile, "r ")
If not inf:
Print ("env file cannot be opened for open! ")
For line in inf. readlines ():
K, v = line. split ("= ")
Self. envs [k] = v
Inf. close ()

Def ClearAll (self ):
Self. envs. clear ()

Def AddEnv (self, k, v ):
Self. envs [k] = v

Def RemoveEnv (self, k ):
Del self. envs [k]

Def PrintAll (self ):
For k, v in self. envs. items ():
Print (k + "=" + v)

If _ name _ = "_ main __":
MyEnv = MyEnv ()
MyEnv. SetEnvFile ("c :\\ myenv.txt ")
MyEnv. Load ()
MyEnv. AddEnv ("MYDIR", "c: \ mydir ")
MyEnv. AddEnv ("MYDIR2", "c: \ mydir2 ")
MyEnv. AddEnv ("MYDIR3", "c: \ mydir3 ")
MyEnv. Save ()
MyEnv. PrintAll ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.