• 【python零基础入门学习】python基础篇之系统模块调用shell命令执行(四)


     本站以分享各种运维经验和运维所需要的技能为主

    《python》:python零基础入门学习

    shell》:shell学习

    《terraform》持续更新中:terraform_Aws学习零基础入门到最佳实战

    《k8》暂未更新

    docker学习》暂未更新

    《ceph学习》ceph日常问题解决分享

    《日志收集》ELK+各种中间件

    《运维日常》持续更新中

    系统管理模块:

    shutil模块:

    用于执行一些shell操作

    1. import shutil
    2. import os
    3. f1 = open('/etc/hosts', 'rb')
    4. f2 = open('/tmp/zj.txt', 'wb')
    5. shutil.copyfileobj(f1 , f2)
    6. f1.close()
    7. f2.close()
    8. #拷贝文件,cp /etc/hosts /tmp/zhuji
    9. shutil.copy('/etc/hosts','/tmp/yff')
    10. shutil.copy('/etc/hosts','/tmp/yff.txt')
    11. #cp -p /etc/hosts /tmp/zhuji
    12. shutil.copy2('/etc/hosts','/tmp/yff2')
    13. #cp -r /etc/security /tmp/anquan
    14. shutil.copytree('/etc/security','/tmp/anquan')
    15. #mv /tmp/anquan /var/tmp/
    16. shutil.move('/tmp/anquan','/var/tmp')
    17. #chown bob.bob /tmp/yyf
    18. shutil.chown('/tmp/yff.txt',user='yyf',group='yyf')
    19. shutil.chown('/tmp/yff',user='yyf',group='yyf')
    20. shutil.chown('/tmp/yff2',user='yyf',group='yyf')
    21. #rm -rf /var/tmp/anquan ---只能删除目录
    22. shutil.rmtree('/var/tmp/anquan')
    23. #rm -rf /tmp/yyf ----删除文件
    24. os.remove('/tmp/yff2')

    subprocess模块:

    用于调用系统命令

    1. >>> import subprocess
    2. >>> result = subprocess.run('id root', shell=True)
    3. uid=0(root) gid=0(root) 组=0(root)
    4. >>> result = subprocess.run('id root ; id yyf', shell=True)
    5. uid=0(root) gid=0(root) 组=0(root)
    6. uid=1003(yyf) gid=1003(yyf) 组=1003(yyf)
    7. >>> result = subprocess.run('id root ; id ddd', shell=True)
    8. uid=0(root) gid=0(root) 组=0(root)
    9. id: ddd: no such user
    10. >>> result.args
    11. 'id root ; id ddd'
    12. >>> result.returncode -----相当于 shell 的$?
    13. 1
    14. #如果不希望把命令的执行结果打印在屏幕上,可以使用以下方式:
    15. >>> import subprocess
    16. >>> result = subprocess.run('id root; id sss', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    17. >>> result.stderr
    18. b'id: sss: no such user\n'
    19. >>> result.stdout
    20. b'uid=0(root) gid=0(root) \xe7\xbb\x84=0(root)\n'
    21. >>> result.stdout.decode()
    22. 'uid=0(root) gid=0(root) 组=0(root)\n'
    23. >>>
    24. py:
    25. import subprocess
    26. result = subprocess.run('id root ; id fff ', shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    27. print(result.stderr)
    28. print(result.stdout)
    29. print(result.stdout.decode())
    30. 测试结果:
    31. b'id: fff: no such user\n'
    32. b'uid=0(root) gid=0(root) \xe7\xbb\x84=0(root)\n'
    33. uid=0(root) gid=0(root) 组=0(root)

    ping脚本:

    1. import sys
    2. import subprocess
    3. def ping(host):
    4.     result = subprocess.run(
    5.         'ping -c2 %s &> /dev/null' % host , shell=True
    6.     )
    7.     if result.returncode == 0 :
    8.         print('%s:up' % host)
    9.     else:
    10.         print('%s:down' % host)
    11. if __name__ == '__main__':
    12.     ping(sys.argv[1])

    编程常用语法风格以及习惯:

    语法风格:

    链示多重赋值:

    1. >>> a=b=[10,20]
    2. >>> b.append(40)
    3. >>> a
    4. [10, 20, 40]
    5. >>> b
    6. [10, 20, 40]

    多元变量赋值:

    1. >>> a,b = 10 ,20
    2. >>> a
    3. 10
    4. >>> b
    5. 20
    6. >>> c, d = (10,20)
    7. >>> c
    8. 10
    9. >>> d
    10. 20
    11. >>> e, f = [10, 20 ]
    12. >>> e
    13. 10
    14. >>> b
    15. 20
    16. >>> a = [100]
    17. >>> a
    18. [100]
    19. >>> g, f = 'ab'
    20. >>> g
    21. 'a'
    22. >>> f
    23. 'b'
    24. 两个变量互换
    25. >>> t = a
    26. >>> a = b
    27. >>> b = t
    28. >>> a
    29. 20
    30. >>> b
    31. [100]
    32. >>> a , b = b ,a
    33. >>> a
    34. [100]
    35. >>> b
    36. 20

    合法标识符:

    1. >>> import keyword
    2. >>> keyword.kwlist
    3. ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
    4. >>> 'pass' in keyword.kwlist
    5. True
    6. >>> keyword.iskeyword('is')
    7. True

    內建: 

    內建不是关键字,可以被覆盖,除非你不用它

    len = 100

    len('abc')  -----无法使用原来的功能

    模块文件布局:

    1. ```python
    2. #!/usr/local/bin/python3        # 解释器
    3. """模块文件名
    4. 模块文件的说明文字,即文档字符串,用于help帮助
    5. """
    6. import sys                      # 模块导入
    7. from random import randint, choice
    8. hi = 'Hello World'              # 全局变量
    9. debug = True
    10. class MyClass:                  # 类的定义
    11.     pass
    12. def func1():                    # 函数定义
    13.     pass
    14. if __name__ == '__main__':      # 主程序代码
    15.     func1()
    16. ```
    17. #!/usr/local/bin/python3      ---解释器
    18. """演示模块
    19. 辣鸡
    20. """
    21. hi = 'hello shabichao'  # 全局变量之后才可以调用
    22. def pstar(n=30):
    23.     "用于打印n个星号"
    24.     print('*' * n)
    25. if __name__ == '__main__':
    26.     print(hi)
    27.     pstar()
    28.     pstar(50)
    29. >>> import star
    30. >>> help(star)
    31. Help on module star:
    32. NAME
    33.     star - 演示模块
    34. DESCRIPTION
    35.     辣鸡
    36. FUNCTIONS
    37.     pstar(n=30)
    38.         用于打印n个星号
    39. DATA
    40.     hi = 'hello shabichao'
    41. FILE
    42.     /root/nsd1907/py01/day03/star.py

    判断文件是否存在:

    1. >>> import os
    2. >>> os.path.ex
    3. os.path.exists(      os.path.expanduser(  os.path.expandvars(  os.path.extsep     
    4. >>> os.path.ex
    5. os.path.exists(      os.path.expanduser(  os.path.expandvars(  os.path.extsep     
    6. >>> os.path.exists('/tmp/yff')
    7. True
    8. >>> os.path.exists('/tmp/yffdd')
    9. False

    编程思路:

    1. 1. 发呆。思考程序的动作方式(交互?非交互?)
    2. ```shell
    3. 文件名: /
    4. 文件已存在,请重试。
    5. 文件名: /etc/hosts
    6. 文件已存在,请重试。
    7. 文件名: /tmp/abc.txt
    8. 请输入文件内容,在单独的一行输入end结束。
    9. (end to quit)> hello world!
    10. (end to quit)> how are you?
    11. (end to quit)> the end
    12. (end to quit)> end
    13. # cat /tmp/abc.txt
    14. hello world!
    15. how are you?
    16. the end
    17. ```
    18. 2. 分析程序有哪些功能,把这些功能编写成函数
    19. ```python
    20. def get_fname():
    21.     '用于获取文件名'
    22. def get_content():
    23.     '用于获取内容'
    24. def wfile(fname, content):
    25.     '用于将内容content,写入文件fname'
    26. ```
    27. 3. 编写程序的主体,按一定的准则调用函数
    28. ```python
    29. def get_fname():
    30.     '用于获取文件名'
    31. def get_content():
    32.     '用于获取内容'
    33. def wfile(fname, content):
    34.     '用于将内容content,写入文件fname'
    35. if __name__ == '__main__':
    36.     fname = get_fname()
    37.     content = get_content()
    38.     wfile(fname, content)
    39. ```
    40. 4. 完成每一个具体的函数
     实例:
    1. """创建文件
    2. 这是一个用于创建文件的脚本,用到的有三个函数
    3. """
    4. import os
    5. def get_fname():
    6.     '用于获取文件名'
    7.     while 1 :
    8.         fname =  input('文件名: ')
    9.         if not os.path.exists(fname):
    10.             break
    11.         print('文件已存在,请重新输入: ')
    12.     return fname
    13. def get_content():
    14.     '用于获取内容'
    15.     content = []
    16.     print('请输入文件内容,在单独的一行输入end结束')
    17.     while 1:
    18.         line = input('(end to quit)> ')
    19.         if line == 'end':
    20.             break
    21.         #content.append(line + '\n')
    22.         content.append(line)
    23.     return content
    24.     # print('请输入文件内容,在单独的一行输入end结束')
    25.     # f = open(fname,'w')
    26.     # while if q != end :
    27.     # content = f.writelines([q = input('(end to quit)>: ')])
    28. def wfile(fname,content):
    29.     '用于将内容content,写入文件fname'
    30.     with open(fname, 'w') as fobj:
    31.         fobj.writelines(content)
    32.     # fobj = open(fname,'w')
    33.     # fobj.writelines(content)
    34.     # fobj.close()
    35. if __name__ == '__main__':
    36.     fname = get_fname()
    37.     content = get_content()
    38.     print(content)
    39.     content = ['%s\n' % line for line in content]
    40.     wfile(fname, content)

     序列对象:

    包括字符串 列表 元组

    1. #list用于将某些数据转成列表 
    2. >>> list(range(10))
    3. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    4. >>> list('abc')
    5. ['a', 'b', 'c']
    6. #tuple用于将某些数据转成元组
    7. >>> tuple('abc')
    8. ('a', 'b', 'c')
    9. >>> tuple(range(10))
    10. (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    11. >>> len('asdasd')
    12. 6
    13. #reversed 用于翻转
    14. >>> alist = [ 10 , 8 , 25 , 1, 100]
    15. >>> list(reversed(alist))
    16. [100, 1, 25, 8, 10]
    17. >>> for i in reversed(alist):
    18. ...    print(i)
    19. #sorted用于排序,默认升序
    20. >>> sorted(alist)
    21. [1, 8, 10, 25, 100]
    22. #enumerate 用于获取下标和值
    23. >>> user = ['tom','yyf','chao']
    24. >>> list(enumerate(user))
    25. [(0, 'tom'), (1, 'yyf'), (2, 'chao')]
    26. >>> for i in enumerate(user):
    27. ...    print(i)
    28. ...
    29. (0, 'tom')
    30. (1, 'yyf')
    31. (2, 'chao')
    32. >>> for i, name in enumerate(user):
    33. ...    print(i,name)
    34. ...
    35. 0 tom
    36. 1 yyf
    37. 2 chao
    38. >>> print(i)  ------一次次的赋值给变量i
    39. 2

    字符串:

    1. 格式化操作符:
    2. >>> '%s is %s years old' % ('tom',20)
    3. 'tom is 20 years old'
    4. >>> '%s is %d years old' % ('tom',20)
    5. 'tom is 20 years old'
    6. >>> '%s is %f years old' % ('tom',20.5)
    7. 'tom is 20.500000 years old'
    8. >>> '%s is %d years old' % ('tom',20.5)
    9. 'tom is 20 years old'
    10. >>> '%d is %d years old' % ('tom',20) -----tom转不成数字
    11. Traceback (most recent call last):
    12.   File "", line 1, in <module>
    13. TypeError: %d format: a number is required, not str
    14. >>> '%s is %.1f years old' % ('tom',20.5) ------%.1f 指保留1位小数
    15. 'tom is 20.5 years old'
    16. >>> '%10s%8s' % ('tom',20.5)  -----正数向右对齐
    17. '      tom    20.5'
    18. >>> '%10s%8s' % ('tom','age')
    19. '      tom    age'
    20. >>> '%-10s%-8s' % ('tom','age')  ------负数向左对齐
    21. 'tom      age    '
    22. >>> '%-10s%-8s' % ('tom',20)
    23. 'tom      20
    24. #不常用 了解
    25. >>> '%c' % 97  ----将数字根据ascii码转成对应的字符
    26. 'a'
    27. >>> '%c' % 65
    28. 'A'
    29. >>> '%#o' % 10----8进制
    30. '0o12'
    31. >>> '%#x' % 10------16进制
    32. '0xa'
    33. >>> '%e' % 10000-----科学计算法----
    34. '1.000000e+04'  ------e+04  10的4次方
    35. >>> '%8d' % 10
    36. '      10'
    37. >>> '%08d' % 10  -----宽度8  不够的补0
    38. '00000010'
    39. format函数
    40. >>> '{} is {} years old'.format('tom',20)
    41. 'tom is 20 years old'
    42. >>> '{1} is {0} years old'.format('tom',20)
    43. '20 is tom years old'
     format函数:

    创建用户:
    1. """创建用户
    2. 这是一个用于创建用户的脚本,用到有4个函数
    3. """
    4. import sys
    5. import randpass
    6. import subprocess
    7. def add_user(user, passwd, fname):
    8.     #如果用户已存在,则返回,不要继续执行函数
    9.     result = subprocess.run(
    10.         'id %s &> /dev/null' % user, shell=True
    11.     )
    12.     if result.returncode == 0 :
    13.         print('用户已存在')
    14.         #return默认返回None,类似于break,函数遇到return也会提前结束
    15.         return
    16.     # 创建用户, 设置密码
    17.     subprocess.run(
    18.         'useradd %s' % user, shell=True
    19.     )
    20.     subprocess.run(
    21.         'echo %s | passwd --stdin %s' % (passwd,user),shell=True
    22.     )
    23.     #写入文件
    24.     info = """用户信息:
    25.     用户名: %s
    26.     密码: %s
    27.     """ % (user,passwd)
    28.     with open(fname,'a') as fobj:
    29.         fobj.write(info)
    30. if __name__ == '__main__':
    31.     user = sys.argv[1]
    32.     passwd = randpass.mk_pass2()
    33.     fname = sys.argv[2]
    34.     add_user(user,passwd,fname)
    原始字符串操作符:
    1. >>> win_path = 'c:\temp'
    2. >>> print(win_path)
    3. c:      emp
    4. >>> wpath = r'c:\temp'
    5. >>> print(wpath)
    6. c:\temp
    7. >>> win_path = 'c:\\temp'
    8. >>> print(win_path)
    9. c:\temp
    10. >>> a = r'c:\tem\tec'
    11. >>> print(a)
    12. c:\tem\tec
    格式化输出:
    1. >>> '+%s+' % ('*' * 50)
    2. '+**************************************************+'
    3. >>> 'hello world'.center(48)
    4. '                  hello world                  '
    5. >>> '+hello world+'.center(50)
    6. '                  +hello world+                  '
    7. >>> '+%19s%-18s+' % ('hello','world')
    8. '+              helloworld            +'
    9. >>> 'hello world'.center(48,'*')
    10. '******************hello world*******************'
    11. >>>
    12. >>> 'hello world'.ljust(48,'a')
    13. 'hello worldaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    14. >>> 'hello world'.ljust(48,'#')
    15. 'hello world#####################################'
    16. >>> 'hello world'.rjust(48,'%')
    17. '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%hello world'
    18. >>>
    19. >>> '+' + 'hello world'.center(48,'*') + '+'
    20. '+******************hello world*******************+'
    21. >>> '+%s+' % 'hello'.center(50)
    22. '+                      hello                      +'
    23. >>> 'hello'.upper()  # 转大写
    24. 'HELLO'
    25. >>> 'HELLO'.lower()  # 转小写
    26. 'hello'
    27. >>> 'hello'.startswith('h'# 字符串以h开头吗?
    28. True
    29. >>> 'hello'.startswith('he'# 字符串以he开头吗?
    30. True
    31. >>> 'hello'.endswith('ab')    # 字符串以ab结尾吗?
    32. False
    33. >>> 'hao123'.islower()  # 字母都是小写的吗?
    34. True
    35. >>> 'hao123'.isupper()  # 字母都是大写的吗?
    36. False
    37. >>> '1234'.isdigit()    # 所有的字符都是数字吗?
    38. True
    39. # 判断是不是所有的字符都是数字字符
    40. >>> s = '1234@11'
    41. >>> for ch in s:
    42. ...  if ch not in '0123456789':
    43. ...    print(False)
    44. ...    break
    45. ... else:
    46. ...  print(True)
    47. ...
    48. False

    下一篇文将会教python的常用数据类型:列表,元组,字典,集合,想学习的同学一起学习。

  • 相关阅读:
    【中兴】web训练营~一文带你走进前端 | 百图制作
    202203-3 CCF 计算资源调度器 (运用stl容器模拟 满分题解)
    记录在vue开发上遇到的一些问题
    应对广告虚假流量,app广告变现该如何风控?
    【目标检测】37、FreeAnchor: Learning to Match Anchors for Visual Object Detection
    Pr:导出设置之字幕
    【算法leetcode】1051. 高度检查器(rust和go)
    读《额尔古纳河右岸》
    WMS系统出库管理:优化仓储流程
    Niantic CEO:AR有望取代二维码,理想的AR眼镜还需3-5年
  • 原文地址:https://blog.csdn.net/zerotoall/article/details/132693877