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 ()