Python 封装cmd 执行命令

1、利用shell中执行成功返回0 失败非零  封装成函数

 # coding: utf-8
 from subprocess import Popen, PIPE, STDOUT
import sys

def run_cmd(cmd): p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) stdout, stderr = p.communicate() return p.returncode, stdout.strip() code, out = run_cmd('ls /')
 if code:
  print '命令执行成功'
else:
   print '命令执行失败'
   sys.exit(1)

2、修改用户与所属组

import pwd
 
uid, gid = pwd.getpwnam(os_mysql_user).pw_uid, pwd.getpwnam(os_mysql_group).pw_gid
data_path = '/data/3306'

#------ 创建数据目录及相关子目录和文件----
if not os.path.exists(data_path):
    os.makedirs(data_path)
os.chown(data_path, uid, gid)

data_path_list = ['data', 'tmpdir']
for data_path_item in data_path_list:
    data_path_dir = os.path.join(data_path,data_path_item)
    if not os.path.exists(data_path_dir):
        os.makedirs(data_path_dir)
    os.chown(data_path_dir,uid,gid)

 

posted @ 2020-04-01 16:20  QQmini  阅读(968)  评论(0编辑  收藏  举报