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

python在shell中环境变量使用的更多相关文章

  1. shell中环境变量

    Linux中环境变量包括系统级和用户级,系统级的环境变量是每个登录到系统的用户都要读取的系统变量,而用户级的环境变量则是该用户使用系统时加载的环境变量. 所以管理环境变量的文件也分为系统级和用户级的, ...

  2. awk中使用shell的环境变量

    awk中使用shell的环境变量一:"'$var'"这种写法大家无需改变用'括起awk程序的习惯,是老外常用的写法.如:var="test"awk 'BEGIN ...

  3. Linux中环境变量文件及配置

    Linux中环境变量文件及配置   一.环境变量文件介绍 转自:http://blog.csdn.net/cscmaker/article/details/7261921 Linux中环境变量包括系统 ...

  4. Linux中环境变量文件及配置(转载)

    一.环境变量文件介绍 转自:http://blog.csdn.net/cscmaker/article/details/7261921 Linux中环境变量包括系统级和用户级,系统级的环境变量是每个登 ...

  5. Linux编程 11(shell全局环境变量与局变环境变量)

    一.概述 在linux中,很多程序和脚本都通过环境变量来获取系统信息,存储临时数据,配置信息.环境变量是指用来存储有关shell会话和工作环境信息,允许你在内存中存储数据,以便程序或shell中运行的 ...

  6. Linux中环境变量中文件执行顺序

        Linux 的变量可分为两类:环境变量和本地变量   环境变量:或者称为全局变量,存在于所有的shell 中,在你登陆系统的时候就已经有了相应的系统定义的环境变量了.Linux 的环境变量具有 ...

  7. CentOS中环境变量和配置文件

    什么是环境变量 bash shell用一个叫做 环境变量(environment variable) 的特性来存储有关shell会话和工作环境的信息.即允许在内存中存储数据,使得在程序或shell中运 ...

  8. Linux中环境变量文件

    一.环境变量文件介绍 转自:http://blog.csdn.net/cscmaker/article/details/7261921 Linux中环境变量包括系统级和用户级,系统级的环境变量是每个登 ...

  9. SHELL 中的变量

    变量的分类 系统环境变量 系统本身所有,通常为大写字母 系统变量通过 set 或 declare 指令进行查看 UDV 变量(user defined variable ) 用户创建和维护,建议大写 ...

随机推荐

  1. Python往kafka生产消费数据

    安装 kafka:  pip install kafka-python 生产数据 from kafka import KafkaProducer import json ''' 生产者demo 向te ...

  2. python读取txt文件时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x8e in position 8: illegal multibyte sequence

    python读取文件时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x8e in position 8: illegal multibyte ...

  3. 阿里云端安装mysql

    首先查看系统版本,是64位的centos7 file /sbin/init 安装指南如下 https://www.cnblogs.com/thinkingandworkinghard/p/671125 ...

  4. 在xshell中安装python3.6

    首先下载python安装包 wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz 然后解压 tar Jxvf Python- ...

  5. IO框架:asyncio 下篇

    动态添加协程 在实战之前,我们要先了解下在asyncio中如何将协程态添加到事件循环中的.这是前提. 如何实现呢,有两种方法: 主线程是同步的 import time import asyncio f ...

  6. Django :执行 python manage.py makemigrations 时报错 TypeError: __init__() missing 1 required positional argument: 'on_delete'

    原因 执行命令 python manage.py makemigrations 报错 TypeError: __init__() missing 1 required positional argum ...

  7. 《Python基础教程》第四章:字典

    字典中的值没有特殊的顺序 电话号码(以及其他可能以0开头的数字)应该表示为数字字符串,而不是整数 dict函数可以通过序列对建立字典 clear方法清除字典中所有的项.这是个原地操作,无返回值 get ...

  8. 使用Sendinput以及GetAsyncKeyState来模拟按键延时

    Code: #include <windows.h> #include <tchar.h> #include <iostream> BOOL flag = TRUE ...

  9. Hadoop-No.8之时间戳

    要获得良好的HBase的模式设计,要正确的理解和使用时间错.在HBase中,时间戳的作用如下所述. 时间戳决定了在put请求修改记录时那些记录更新 时间戳决定了一条记录的多个版本在返回时的排序 时间戳 ...

  10. spark写数据入kafka示范代码

    一.pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...