python 之 subprocesss 模块、configparser 模块

时间:2023-03-28 10:17:38

6.18 subprocesss 模块

常用dos命令:

cd : changedirectory 切换目录

tasklist:查看任务列表

tasklist | findstr python :查看任务列表并筛选出python任务的信息
# python.exe 12360 Console 1 11,024 K

/?:查看命令使用方法

taskkill :利用PID结束任务
# D:\code>taskkill /F /PID 12360

linux系统(了解):

ps aux | grep python
kill -9 PID #-9表示强制结束任务
import subprocess
obj=subprocess.Popen('dir',
shell=True,
stdout=subprocess.PIPE, #正确管道
stderr=subprocess.PIPE #错误管道
)

print(obj) #<subprocess.Popen object at 0x000001F06771A3C8>

res1=obj.stdout.read() #读取正确管道内容
print('正确结果1: ',res1.decode('gbk'))

res2=obj.stdout.read()
print('正确结果2: ',res2.decode('gbk')) #只能取一次,取走了就空了

res3=obj.stderr.read() #读取错误管道内容
print('错误结果:',res3.decode('gbk'))

6.19 configparser 模块

my.ini文件:

[egon]
age=18
pwd=123
sex=male
salary=5.1
is_beatifull=True

[lsb]
age=30
pwd=123456
sex=female
salary=4.111
is_beatifull=Falase
import configparser

config=configparser.ConfigParser()
config.read('my.ini')

secs=config.sections()
print(secs) #['egon', 'lsb']

print(config.options('egon')) #['age', 'pwd', 'sex', 'salary', 'is_beatifull']

age=config.get('egon','age') #18 <class 'str'>
age=config.getint('egon','age') #18 <class 'int'>
print(age,type(age))

salary=config.getfloat('egon','salary')
print(salary,type(salary)) #5.1 <class 'float'>

b=config.getboolean('egon','is_beatifull')
print(b,type(b)) #True <class 'bool'>