python在shell中環境變量使用


1、用Python Shell設置或獲取環境變量的方法:

設置系統環境變量

os.environ['環境變量名稱']='環境變量值' #其中key和value均為string類型

os.putenv('環境變量名稱', '環境變量值')

獲取系統環境變量

os.environ['環境變量名稱']

os.getenv('環境變量名稱')



實例一、

In [52]: output=subprocess.check_output(["head -c 16 /dev/urandom | od -An -t x | tr -d ' '"], shell=True)                           

In [53]: print(output)                                                                                                               
b'3512c668547cd983cb48ccf05b0ccedf\n'

In [67]: output.strip()                                                                                                              
Out[67]: b'3512c668547cd983cb48ccf05b0ccedf'

In [72]: output.strip().strip('b')                                                                                                   
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-72-d12ac1d7dec8> in <module>
----> 1 output.strip().strip('b')

TypeError: a bytes-like object is required, not 'str'


In [73]: os.environ["token"]=str(output.strip()).strip('b')                                                                          

In [74]: os.getenv["token"]                                                                                                         
Out[74]: "'3512c668547cd983cb48ccf05b0ccedf'"



實例二、

os.environ["user"]="jenkins"

os.getenv["user"]

'jenkins'

 

os.path.expanduser(path)                            把path中包含的”~”和”~user”轉換成用戶目錄

實例三、

os.path.expanduser("~")

'/home/mysql'

 

os.path.expandvars(path)                      根據環境變量的值替換path中包含的”$name”和”${name}”

實例四、

os.environ["user"]="jenkins"

os.path.expandvars("$user/mysql")

'jenkins/mysql'
 
 

2、對文件內容中定義的變量替換成真實的值

特別注意:原文件必須是 python文件,否則不能替換,

如果想要修改文件中的某一行或者某一個位置的內容,在python中是沒有辦法直接實現的,只能先把文件所有的內容全部讀取出來,然后進行匹配修改后寫入到新的文件中。


例如想要把文件中的變量替換為真實的值需要進行如下操作:

查看原文件內容

注意:下面TOKEN不能寫成$TOKEN , 寫入后查看文件會變成空格

cat > /k8s/profile/token.py << EOF
TOKEN,kubelet-bootstrap,10001,"system:kubelet-bootstrap"
EOF


定義變量

In [7]: output=subprocess.check_output(["head -c 16 /dev/urandom | od -An -t x | tr -d ' '"], shell=True)                            

In [9]: token=str(output.decode('utf8').strip()).strip('b')                                                                          

In [10]: print(token)                                                                                                                
d3f4e95e05dfe34ea87217a55fb75bac


開始替換

In [3]: os.chdir('/etc/kubernetes/')                                                                                                 

In [4]: if os.path.exists('token.csv'): 
   ...:         os.remove('token.csv') 


In [56]: f = open('/k8s/profile/token.py','r',encoding='utf-8')

In [57]: f_new = open('/etc/kubernetes/token.csv','w',encoding='utf-8')

In [58]: for line in f:
    ...:     if "TOKEN" in line:
    ...:         line = line.replace('TOKEN',token)
    ...:     f_new.write(line)
    ...: f.close()
    ...: f_new.close()




3、替換文件中的主機名、ip 變量

cat > hostname_ip_py << EOF
#!/usr/bin/python
# -*- codinig: utf-8 -*-

from __future__ import print_function
import os, sys, stat
import shutil
import tarfile
import subprocess

# 定義環境變量

# 定義主機名
NODE_NAME = subprocess.check_output(["hostname"], shell=True)
NODE_NAME = str(NODE_NAME.decode('utf8').strip()).strip('b')

# 定義主機ip
NODE_IP = subprocess.check_output(["hostname -i | awk '{print $NF}'"], shell=True)
NODE_IP = str(NODE_IP.decode('utf8').strip()).strip('b')

ETCD_NODES = "test1=https://192.168.0.91:2380,test2=https://192.168.0.92:2380,test3=https://192.168.0.93:2380"

# 創建 etcd.service文件
f = open('/k8s/profile/etcd.service.template.py', 'r', encoding='utf-8')
f_new = open('/etc/systemd/system/etcd.service', 'w', encoding='utf-8')
for line in f:
    if "NODE_NAME" in line:
        line = line.replace('NODE_NAME', NODE_NAME)
    elif "NODE_IP" in line:
        line = line.replace('NODE_IP', NODE_IP)
    elif "ETCD_NODES" in line:
        line = line.replace('ETCD_NODES', ETCD_NODES)
    f_new.write(line)
print("替換完成")
f.close()
f_new.close()
EOF





 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM