在python程序中运行shell脚本
2018-02-08 14:50
453 查看
#!/usr/bin/python # 导入各种模块 import sys ... # 各种变量 consul_ip = sys.argv[2] install_path = ... ... # 使用os.system()在python执行shell命令 os.system('mkdir -p '+install_path) ... # 进一步对变量进行处理成 “export install_path= /opt” 形式 def create_env_str(env_dict): import pdb pdb.set_trace() env_str = "" for k, v in env_dict.items(): env_str = env_str + "export " + k + "=" + v + "\n" return env_str # 将变量设置成字典,以便传递到shell脚本中使用 env_dict = { "install_path": install_path, "current_dir": current_dir, "req_path": req_path, "deps_path": deps_path, "packages": packages, "log_path": log_path, "consul_ip": sys.argv[2] } # 创建可执行shell脚本 def gen_script_fire(env_dict): env = create_env_str(env_dict) # shell中要执行的具体的指令 cmd = ''' #此处是往“/tmp/vmware-exporter-systemctl”文件中写内容,配置服务 sudo cat >/tmp/vmware-exporter-systemctl<<EOF [Unit] Description=Vmware Exporter After=network.target [Service] ExecStart=/usr/bin/python ${install_path}/vmware_exporter/vmware_exporter/vmware_exporter.py -c ${consul_ip} [Install] WantedBy=default.target EOF ... ''' # 开始写 with open('/tmp/service_firewalld.sh', 'w+') as f: f.write("#!/bin/bash" + "\n") f.write(env) f.write(cmd) def run(cmd): # 用subprocess.call 方法执行shell脚本 ret = subprocess.call(cmd, shell=True) if ret != 0: sys.exit('Exec cmd %s error, return value: %s' % (cmd, str(ret))) def run_script(): run("sudo bash /tmp/service_firewalld.sh") gen_script_fire(env_dict) run_script()
注意:
cmd= ”’ ”’ 中有expect命令时,可能出现expect spawn not found
错误
原因:expec不是shell中的命令,所以在执行bash shellname.sh时会报错
解决:参考:http://blog.csdn.net/chinabluexfw/article/details/7461944
1. 不用
bash或
sh执行shell脚本,使用
./shellname.sh命令执行
2. 使用
chmod +x shellname.sh赋权限
相关文章推荐
- linux的shell脚本运行python程序
- 怎样运行shell脚本程序
- PHP执行shell脚本运行程序不产生core文件
- 第一次用shell脚本来自动运行带参程序
- shell脚本命令 运行python文件&python命令行运行python代码
- 使用shell脚本批量运行caffe程序
- Linux:shell脚本反复运行同一个程序
- 在cmd下运行Python脚本+如何使用Python Shell
- 如何在Windows下开发Python:在cmd下运行Python脚本+如何使用Python Shell(command line模式和GUI模式)+如何使用Python IDE
- python获取程序运行目录和脚本目录
- PHP执行shell脚本运行程序不产生core文件的方法
- Linux系统-shell脚本运行程序
- 写个shell脚本依次运行每个程序半小时
- shell脚本中用指定用户运行程序
- 运行java程序shell脚本
- Shell脚本运行hive语句 | hive以日期建立分区表 | linux schedule程序 | sed替换文件字符串 | shell推断hdfs文件文件夹是否存在
- python运行spark脚本程序
- Java后台执行Shell脚本, Java方法不用等待Shell程序执行完成并保证关掉Java程序Shell脚本正常运行
- 用shell脚本运行Java程序
- shell脚本运行java程序