1. 程式人生 > >python3 json、logging、sys模塊

python3 json、logging、sys模塊

style arm add and 退出 -s 第一個 foo less

json模塊

import json

dic = {name:egon,age:32}
# ------------------------------>序列化
f = open(json.txt,w)
data = json.dumps(dic)
print(data)
print(type(data))
f.write(data)
f.close()

# ------------------------------>返序列化
f = open(json.txt,r)
data = f.read()
dic1 = json.loads(data)
print(dic1) print(type(dic1)) f.close()

二、logging模塊

import logging

logger = logging.getLogger()
fh = logging.FileHandler(test.log)    # 用於寫入日誌文件
ch = logging.StreamHandler()            # 用於輸入到終端

# 自定義格式
formatter = logging.Formatter(%(asctime)s-%(name)s-%(levelname)s-%(message)s)

fh.setFormatter(formatter)
sh.setFormatter(formatter)

logger.addHandler(fh)   
#logger對象可以添加多個fh和sh對象 logger.addHandler(sh) logger.debug(logger debug message) logger.info(logger info message) logger.warning(logger warning message) logger.error(logger error message) logger.critical(logger critical message)

三、sys模塊

import sys
sys.exit(n)  退出程序,正常退出時exit(0)
sys.argv    命令行參數List,第一個元素是程序本身路徑

sys.path    返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值

sys.exit()
import sys

count=1
while count<10:
    print(count)
    if count==8:
        sys.exit()  # 退出程序
    count+=1

print("ending")

  sys.argv

# cmd終端輸入python sys模塊.py egon 666

print("begin..... ")

ret=sys.argv  #  [sys模塊.py‘,"egon",666]
print(ret)    #  [‘sys模塊.py‘, ‘-u‘, ‘egon‘, ‘-p‘, ‘666‘]

username=ret[1]
password=ret[2]

if username==egon and password=="666":
    print("login")

  sys.path

import sys

print(sys.path)# [“C:\Users\Administrator\PycharmProjects\python5期\day13”,"python環境"]  :執行文件的目錄會添加到sys.path

Base_dir=r"C:\Users\Administrator\PycharmProjects\python5期\day12"
sys.path.append(Base_dir)

import lesson1  # 自定義的模塊
lesson1.foo()

python3 json、logging、sys模塊