Python读取环境变量的方法和自定义类分享

WBOY
Release: 2016-06-10 15:18:49
Original
1052 people have browsed it

使用os.environ来读取和修改环境变量:

复制代码 代码如下:

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"])

自定义的python的环境变量类:

复制代码 代码如下:

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!