use Os.environ to read and modify environment variables:
Copy the Code code 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:
Copy the Code code 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 is 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 is 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 ()