当前位置: 首页 > news >正文

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

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

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

《shell》:shell学习

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

《k8》暂未更新

《docker学习》暂未更新

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

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

《运维日常》持续更新中

系统管理模块:

shutil模块:

用于执行一些shell操作

import shutil
import os
f1 = open('/etc/hosts', 'rb')
f2 = open('/tmp/zj.txt', 'wb')
shutil.copyfileobj(f1 , f2)
f1.close()
f2.close()#拷贝文件,cp /etc/hosts /tmp/zhuji
shutil.copy('/etc/hosts','/tmp/yff')
shutil.copy('/etc/hosts','/tmp/yff.txt')#cp -p /etc/hosts /tmp/zhuji
shutil.copy2('/etc/hosts','/tmp/yff2')#cp -r /etc/security /tmp/anquan
shutil.copytree('/etc/security','/tmp/anquan')#mv /tmp/anquan /var/tmp/
shutil.move('/tmp/anquan','/var/tmp')#chown bob.bob /tmp/yyf
shutil.chown('/tmp/yff.txt',user='yyf',group='yyf')
shutil.chown('/tmp/yff',user='yyf',group='yyf')
shutil.chown('/tmp/yff2',user='yyf',group='yyf')#rm -rf /var/tmp/anquan ---只能删除目录
shutil.rmtree('/var/tmp/anquan')
#rm -rf /tmp/yyf ----删除文件
os.remove('/tmp/yff2')

subprocess模块:

用于调用系统命令

>>> import subprocess
>>> result = subprocess.run('id root', shell=True)
uid=0(root) gid=0(root) 组=0(root)>>> result = subprocess.run('id root ; id yyf', shell=True)
uid=0(root) gid=0(root) 组=0(root)
uid=1003(yyf) gid=1003(yyf) 组=1003(yyf)>>> result = subprocess.run('id root ; id ddd', shell=True)
uid=0(root) gid=0(root) 组=0(root)
id: ddd: no such user>>> result.args
'id root ; id ddd'>>> result.returncode -----相当于 shell 的$?
1#如果不希望把命令的执行结果打印在屏幕上,可以使用以下方式:
>>> import subprocess
>>> result = subprocess.run('id root; id sss', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> result.stderr
b'id: sss: no such user\n'
>>> result.stdout
b'uid=0(root) gid=0(root) \xe7\xbb\x84=0(root)\n'
>>> result.stdout.decode()
'uid=0(root) gid=0(root) 组=0(root)\n'
>>>py:
import subprocess
result = subprocess.run('id root ; id fff ', shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print(result.stderr)
print(result.stdout)
print(result.stdout.decode())测试结果:
b'id: fff: no such user\n'
b'uid=0(root) gid=0(root) \xe7\xbb\x84=0(root)\n'
uid=0(root) gid=0(root) 组=0(root)

ping脚本:

import sys
import subprocessdef ping(host):result = subprocess.run('ping -c2 %s &> /dev/null' % host , shell=True)if result.returncode == 0 :print('%s:up' % host)else:print('%s:down' % host)if __name__ == '__main__':ping(sys.argv[1])

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

语法风格:

链示多重赋值:

>>> a=b=[10,20]
>>> b.append(40)
>>> a
[10, 20, 40]
>>> b
[10, 20, 40]

多元变量赋值:

>>> a,b = 10 ,20
>>> a
10
>>> b
20
>>> c, d = (10,20)
>>> c
10
>>> d
20
>>> e, f = [10, 20 ]
>>> e
10
>>> b
20
>>> a = [100]
>>> a
[100]
>>> g, f = 'ab'
>>> g
'a'
>>> f
'b'两个变量互换>>> t = a
>>> a = b
>>> b = t
>>> a
20
>>> b
[100]
>>> a , b = b ,a 
>>> a
[100]
>>> b
20

合法标识符:

>>> import keyword
>>> keyword.kwlist
['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']
>>> 'pass' in keyword.kwlist
True
>>> keyword.iskeyword('is')
True

內建: 

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

len = 100

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

模块文件布局:

```python
#!/usr/local/bin/python3         # 解释器
"""模块文件名模块文件的说明文字,即文档字符串,用于help帮助
"""
import sys                       # 模块导入
from random import randint, choicehi = 'Hello World'               # 全局变量
debug = Trueclass MyClass:                   # 类的定义passdef func1():                     # 函数定义passif __name__ == '__main__':       # 主程序代码func1()
```
#!/usr/local/bin/python3       ---解释器
"""演示模块辣鸡
"""
hi = 'hello shabichao'  # 全局变量之后才可以调用def pstar(n=30):"用于打印n个星号"print('*' * n)if __name__ == '__main__':print(hi)pstar()pstar(50)>>> import star
>>> help(star)
Help on module star:
NAMEstar - 演示模块
DESCRIPTION辣鸡
FUNCTIONSpstar(n=30)用于打印n个星号
DATAhi = 'hello shabichao'
FILE/root/nsd1907/py01/day03/star.py

判断文件是否存在:

>>> import os
>>> os.path.ex
os.path.exists(      os.path.expanduser(  os.path.expandvars(  os.path.extsep       
>>> os.path.ex
os.path.exists(      os.path.expanduser(  os.path.expandvars(  os.path.extsep       
>>> os.path.exists('/tmp/yff')
True
>>> os.path.exists('/tmp/yffdd')
False

编程思路:

1. 发呆。思考程序的动作方式(交互?非交互?)
```shell
文件名: /
文件已存在,请重试。
文件名: /etc/hosts
文件已存在,请重试。
文件名: /tmp/abc.txt
请输入文件内容,在单独的一行输入end结束。
(end to quit)> hello world!
(end to quit)> how are you?
(end to quit)> the end
(end to quit)> end
# cat /tmp/abc.txt
hello world!
how are you?
the end
```
2. 分析程序有哪些功能,把这些功能编写成函数
```python
def get_fname():'用于获取文件名'
def get_content():'用于获取内容'
def wfile(fname, content):'用于将内容content,写入文件fname'
```
3. 编写程序的主体,按一定的准则调用函数
```python
def get_fname():'用于获取文件名'
def get_content():'用于获取内容'
def wfile(fname, content):'用于将内容content,写入文件fname'
if __name__ == '__main__':fname = get_fname()content = get_content()wfile(fname, content)
```
4. 完成每一个具体的函数

 实例:

"""创建文件这是一个用于创建文件的脚本,用到的有三个函数
"""
import osdef get_fname():'用于获取文件名'while 1 :fname =  input('文件名: ')if not os.path.exists(fname):breakprint('文件已存在,请重新输入: ')return fnamedef get_content():'用于获取内容'content = []print('请输入文件内容,在单独的一行输入end结束')while 1:line = input('(end to quit)> ')if line == 'end':break#content.append(line + '\n')content.append(line)return content# print('请输入文件内容,在单独的一行输入end结束')# f = open(fname,'w')# while if q != end :# content = f.writelines([q = input('(end to quit)>: ')])def wfile(fname,content):'用于将内容content,写入文件fname'with open(fname, 'w') as fobj:fobj.writelines(content)# fobj = open(fname,'w')# fobj.writelines(content)# fobj.close()if __name__ == '__main__':fname = get_fname()content = get_content()print(content)content = ['%s\n' % line for line in content]wfile(fname, content)

 序列对象:

包括字符串 列表 元组

#list用于将某些数据转成列表  
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list('abc')
['a', 'b', 'c']
#tuple用于将某些数据转成元组
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple(range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)>>> len('asdasd')
6#reversed 用于翻转
>>> alist = [ 10 , 8 , 25 , 1, 100]
>>> list(reversed(alist))
[100, 1, 25, 8, 10]
>>> for i in reversed(alist):
...     print(i)#sorted用于排序,默认升序
>>> sorted(alist)
[1, 8, 10, 25, 100]#enumerate 用于获取下标和值
>>> user = ['tom','yyf','chao']
>>> list(enumerate(user))
[(0, 'tom'), (1, 'yyf'), (2, 'chao')]
>>> for i in enumerate(user):
...     print(i)
... 
(0, 'tom')
(1, 'yyf')
(2, 'chao')
>>> for i, name in enumerate(user):
...     print(i,name)
... 
0 tom
1 yyf
2 chao
>>> print(i)   ------一次次的赋值给变量i
2

字符串:

格式化操作符:
>>> '%s is %s years old' % ('tom',20)
'tom is 20 years old'
>>> '%s is %d years old' % ('tom',20)
'tom is 20 years old'
>>> '%s is %f years old' % ('tom',20.5)
'tom is 20.500000 years old'
>>> '%s is %d years old' % ('tom',20.5)
'tom is 20 years old'
>>> '%d is %d years old' % ('tom',20) -----tom转不成数字
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> '%s is %.1f years old' % ('tom',20.5) ------%.1f 指保留1位小数
'tom is 20.5 years old'>>> '%10s%8s' % ('tom',20.5)  -----正数向右对齐
'       tom    20.5'
>>> '%10s%8s' % ('tom','age')
'       tom     age'
>>> '%-10s%-8s' % ('tom','age')  ------负数向左对齐
'tom       age     '
>>> '%-10s%-8s' % ('tom',20)
'tom       20#不常用 了解
>>> '%c' % 97  ----将数字根据ascii码转成对应的字符
'a'
>>> '%c' % 65
'A'
>>> '%#o' % 10----8进制
'0o12'
>>> '%#x' % 10------16进制
'0xa'
>>> '%e' % 10000-----科学计算法----
'1.000000e+04'  ------e+04  10的4次方
>>> '%8d' % 10
'      10'
>>> '%08d' % 10  -----宽度8  不够的补0
'00000010'format函数
>>> '{} is {} years old'.format('tom',20)
'tom is 20 years old'
>>> '{1} is {0} years old'.format('tom',20)
'20 is tom years old'

 format函数:

创建用户:

"""创建用户这是一个用于创建用户的脚本,用到有4个函数
"""import sys
import randpass
import subprocessdef add_user(user, passwd, fname):#如果用户已存在,则返回,不要继续执行函数result = subprocess.run('id %s &> /dev/null' % user, shell=True)if result.returncode == 0 :print('用户已存在')#return默认返回None,类似于break,函数遇到return也会提前结束return# 创建用户, 设置密码subprocess.run('useradd %s' % user, shell=True)subprocess.run('echo %s | passwd --stdin %s' % (passwd,user),shell=True)#写入文件info = """用户信息:用户名: %s密码: %s""" % (user,passwd)with open(fname,'a') as fobj:fobj.write(info)if __name__ == '__main__':user = sys.argv[1]passwd = randpass.mk_pass2()fname = sys.argv[2]add_user(user,passwd,fname)

原始字符串操作符:

>>> win_path = 'c:\temp'
>>> print(win_path)
c:      emp
>>> wpath = r'c:\temp'
>>> print(wpath)
c:\temp
>>> win_path = 'c:\\temp'
>>> print(win_path)
c:\temp
>>> a = r'c:\tem\tec'
>>> print(a)
c:\tem\tec

格式化输出:

>>> '+%s+' % ('*' * 50)
'+**************************************************+'
>>> 'hello world'.center(48)
'                  hello world                   '
>>> '+hello world+'.center(50)
'                  +hello world+                   '
>>> '+%19s%-18s+' % ('hello','world')
'+              helloworld             +'>>> 'hello world'.center(48,'*')
'******************hello world*******************'
>>>
>>> 'hello world'.ljust(48,'a')
'hello worldaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
>>> 'hello world'.ljust(48,'#')
'hello world#####################################'
>>> 'hello world'.rjust(48,'%')
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%hello world'
>>>
>>> '+' + 'hello world'.center(48,'*') + '+'
'+******************hello world*******************+'
>>> '+%s+' % 'hello'.center(50)
'+                      hello                       +'>>> 'hello'.upper()  # 转大写
'HELLO'
>>> 'HELLO'.lower()  # 转小写
'hello'
>>> 'hello'.startswith('h')   # 字符串以h开头吗?
True
>>> 'hello'.startswith('he')  # 字符串以he开头吗?
True
>>> 'hello'.endswith('ab')    # 字符串以ab结尾吗?
False
>>> 'hao123'.islower()   # 字母都是小写的吗?
True
>>> 'hao123'.isupper()   # 字母都是大写的吗?
False
>>> '1234'.isdigit()     # 所有的字符都是数字吗?
True# 判断是不是所有的字符都是数字字符
>>> s = '1234@11'
>>> for ch in s:
...   if ch not in '0123456789':
...     print(False)
...     break
... else:
...   print(True)
...
False

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

http://www.lryc.cn/news/165528.html

相关文章:

  • 用python实现基本数据结构【01/4】
  • Ubuntu22.04 install Kafka
  • 实现JSONP请求
  • 如何将安防视频监控系统/视频云存储EasyCVR平台推流到公网直播间?
  • 使用内网负载机(Linux)执行Jmeter性能测试
  • Web自动化测试进阶 —— Selenium模拟鼠标操作
  • Python之函数
  • 泛型工具类型和操作符
  • idea中启动maven项目报错-java: 程序包lombok.extern.slf4j不存在问题如何解决
  • MyBatis-动态SQL
  • Swift学习内容精选(二)
  • 类欧笔记存档
  • 电能计量远程抄表系统的分析及在物业的应用
  • 计算机网络篇之端口
  • GO语言篇之发布开源软件包
  • Eclipse官网下载历史版本
  • SCI常见词汇表达
  • 使用ref如何获取到input标签中的值
  • 自定义Dynamics 365实施和发布业务解决方案 3. 开箱即用自定义
  • python-pytorch 关于torch.load()和torch.load_state_dict()
  • 关于批量安装多个apk
  • 【案例教学】华为云API对话机器人的魅力—体验AI垃圾分类机器人
  • go基础详解2-go run test
  • 【NVIDIA CUDA】2023 CUDA夏令营编程模型(三)
  • 字节8年经验之谈 —— 冒烟测试、回归测试是什么?
  • FP6102 20V、3A降压开关调节器芯片
  • 魔众携手ModStart上线全新模块市场,支持模板主题
  • 织梦CMS_V5.7任意用户密码重置漏洞复现
  • ESP32通过ali的C LINK4.0接入aliyun阿里云
  • Spring中使用了哪些设计模式