psutil介紹
psutil(python系統和流程實用程序)是一個跨平臺庫,用於在Python中檢索有關正在運行的 進程和系統利用率(CPU,內存,磁盤,網絡,傳感器)的信息。它主要用於系統監視,分析,限制進程資源和運行進程的管理。它實現了UNIX命令行工具提供的許多功能,例如:ps,top,lsof,netstat,ifconfig,who,df,kill,free,nice,ionice,iostat,iotop,uptime,pidof,tty,taskset,pmap.
-
安裝
pip3 install psutil
模塊的功能
系統相關的類
-
cpu
psutil.cpu_times(percpu=False)
將系統CPU時間作爲命名元組返回。每個屬性表示CPU在給定模式下花費的秒數.
- user: 正常進程在用戶模式下執行所花費的時間.
- system: 在內核模式下執行的進程所花費的時間.
字段說明:
- nice : 在用戶模式下執行的niced(優先級)進程所花費的時間.
- iowait: 等待I / O完成所花費的時間.
- irq: 服務硬件中斷所花費的時間.
- softirq: 服務軟件中斷所花費的時間.
- steal: 在虛擬化環境中運行的其他操作系統所花費的時間.
- guest: 在Linux內核的控制下爲客戶操作系統運行虛擬CPU所花費的時間.
- guest_nice: 運行niced guest虛擬機所花費的時間.
當percpu是True返回一個名爲元組的列表在系統上的每個邏輯CPU。列表的第一個元素是指第一個CPU,第二個元素是第二個CPU.
psutil.cpu_percent(interval = None,percpu = False)
返回一個浮點數,表示當前系統範圍的CPU利用率百分比.當percpu是True返回表示利用率的浮點數列表,以每個CPU的百分比表示。列表的第一個元素是指第一個CPU,第二個元素是第二個CPU.
In [9]: psutil.cpu_percent(interval=1) Out[9]: 26.8 In [10]: psutil.cpu_percent(interval=None) Out[10]: 28.8 In [11]: psutil.cpu_percent(interval=1,percpu=True) Out[11]: [5.9, 51.0, 25.7, 26.7]
psutil.cpu_times_percent(interval = None,percpu = False)
與cpu_percent() 相同但提供每個特定cpu時間的利用率百分比.In [13]: psutil.cpu_times_percent(interval=1,percpu=True) Out[13]: [scputimes(user=3.0, nice=0.0, system=0.0, idle=97.0, iowait=0.0, irq=0.0, softirq=0. 0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=2.0, nice=0.0, system=1.0, idle=97.0, iowait=0.0, irq=0.0, softirq=0. 0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=4.0, nice=0.0, system=1.0, idle=95.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0), scputimes(user=98.0, nice=0.0, system=1.0, idle=0.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)]
psutil.cpu_count(logical=True)
返回系統中邏輯CPU的數量. 當logical爲False時返回物理核心數.In [14]: psutil.cpu_count(logical=True) Out[14]: 4 In [17]: psutil.cpu_count(logical=False) Out[17]: 2
獲得可用cpu數量
In [18]: len(psutil.Process().cpu_affinity()) Out[18]: 4
psutil.cpu_stats()
將各種CPU統計信息作爲命名元組返回.
- ctx_switches:啓動後的上下文切換次數
- interrupts: 自引導以來的中斷數.
- soft_interrupts:自引導以來的軟件中斷次數
- syscalls:自引導以來的系統調用次數。
In [19]: psutil.cpu_stats() Out[19]: scpustats(ctx_switches=10645749, interrupts=2838571, soft_interrupts=2770642 , syscalls=0)
psutil.cpu_freq(percpu=False)
將CPU頻率作爲名稱包返回,包括 以Mhz表示的當前,最小和最大頻率.
當percpu爲True並且系統支持每CPU頻率檢索,爲每個CPU返回一個頻率列表,否則返回包含單個元素的列表.In [20]: psutil.cpu_freq(percpu=False) Out[20]: scpufreq(current=3021.204, min=800.0, max=3100.0) In [21]: psutil.cpu_freq(percpu=True) Out[21]: [scpufreq(current=3010.085, min=800.0, max=3100.0), scpufreq(current=3086.548, min=800.0, max=3100.0), scpufreq(current=2993.103, min=800.0, max=3100.0), scpufreq(current=2993.23, min=800.0, max=3100.0)]
內存相關的類
-
memory
psutil.virtual_memory()
- total: 總物理內存
- available: 在沒有系統進入交換的情況下立即提供給進程的內存.
- used: 使用的內存.
- free: 空閒的內存.
- active: 正在使用的內存.
- inactive: 未使用的內存.
- buffers: 緩存文件系統元數據.
- cached: 緩存各種內容.
- shared: 共享內存.
- slab: 內核數據結構緩存
查看物理內存
In [24]: mem = psutil.virtual_memory() In [25]: mem Out[25]: svmem(total=12504399872, available=9867579392, percent=21.1, used=206 4056320, free=7957213184, active=2586599424, inactive=1411063808, buffers=2329 23136, cached=2250207232, shared=330375168, slab=357433344)
psutil.swap_memory()
將系統交換內存統計信息作爲命名元組返回.- total: 總交換內存(以字節爲單位)
- used: 以字節爲單位使用的swap內存
- free: 以字節爲單位的自由交換內存.
- 百分比: 計算的百分比使用率(total - available) / total * 100
- sin: 系統從磁盤交換的字節數.
- sout: 系統從磁盤換出的字節數.
磁盤相關的類
-
disk
psutil.disk_partitions(all=False)
將所有已安裝的磁盤分區作爲命名元組列表返回,包括設備,掛載點和文件系統類型.psutil.disk_usage(path)
In [32]: psutil.disk_usage('/') Out[32]: sdiskusage(total=181488431104, used=12284243968, free=159913754624, percent=7.1)
psutil.disk_io_counters(perdisk=False,nowrap=True)
將系統範圍的磁盤I / O統計信息作爲命名元組返回- read_count: 讀取次數
- write_count: 寫入次數.
- read_bytes: 讀取的字節數
- write_bytes: 寫入的字節數
- read_time: 從磁盤讀取的時間(以毫秒爲單位).
- write_time: 寫入磁盤所花費的時間(以毫秒爲單位).
- busy_time: 在實際I/O上的時間.(以毫秒爲單位).
- read_merged_count: 合併讀取的數量
- write_merged_count: 合併寫入次數.
當perdisk爲True,系統上安裝的每個物理磁盤返回相同的信息,作爲字典.分區名稱爲鍵,命名元組爲值.當nowrap爲True,psutil將在函數調用中檢測並調整這些數字,並將“舊值”添加到“新值”,以便返回的數字將始終增加或保持不變,但永遠不會減少.
psutil.disk_io_counters.cache_clear() 用於使nowrap 緩存無效.In [36]: psutil.disk_io_counters() In [37]: psutil.disk_io_counters(perdisk=True) # 返回字典,所有磁盤信息.
網絡相關的類
-
network
psutil.net_io_counters(pernic=False,nowrap=True)
將系統範圍的網絡I/O統計信息作爲命名元組返回- bytes_sent:發送的字節數.
- bytes_recv:接收的字節數.
- packets_sent:發送的包數.
- packets_recv:接收的包數.
- errin:接收時的錯誤總數.
- errout:發送時的錯誤總數
- dropin:丟棄的傳入數據包總數.
- dropout:丟棄的傳出數據包總數
當pernic爲True,系統上安裝的每個網絡接口返回相同的信息作爲字典,網絡接口名稱作爲鍵,命名元組爲值. psutil.net_io_counters.cache_clear() 用於使nowrap 緩存無效.
In [41]: psutil.net_io_counters() In [42]: psutil.net_io_counters(pernic=True)
psutil.net_connections(kind='inet')
將系統範圍的套接字連接作爲命名元組列表返回.- fd: 套接字文件描述符.
- family:地址簇.
- type:地址類型
- laddr:作爲命名元組的本地地址或 AF_UNIX套接字的情況.
- raddr:作爲命名元組的遠程地址或UNIX套接字的絕對地址
- status:表示TCP連接的狀態.
- pid: 打開套接字的進程的PID.
In [45]: psutil.net_connections() In [45]: psutil.net_connections(kind='inet')
psutil.net_if_addrs()
將與系統上安裝的每個NIC(網絡接口卡)關聯的地址作爲字典返回.鍵爲NIC名稱,值是分配給NIC的每個地址的命名元組列表.- family:地址簇.
- address: 主NIC地址
- netmask:網絡掩碼地址
- broadcast: 廣播地址.
- ptp: 點對點接口上的目標地址.
psutil.net_if_stats()
將有關每個NIC(網絡接口卡)的信息作爲字典返回,鍵是NIC名稱,值是以下字段:- isup: 指示NIC是否已啓動並運行的bool。
- duplex:雙工通信類型.
- speed:以兆位(MB)表示的NIC速度
- mtu:NIC的最大傳輸單位,以字節爲單位.
硬件相關的類
-
傳感器:
psutil.sensors_temperatures()
返回硬件溫度。每個條目都是一個名爲元組,代表某個硬件溫度傳感器.psutil.sensors_fans()
返回硬件風扇速度,每個條目都是一個名爲元組,代表某個硬件傳感器風扇。風扇速度以RPM(每分鐘輪數)表示.psutil.sensors_battery()
將電池狀態信息作爲命名元組返回- percent:電池剩餘百分比
- secsleft: 電池電量耗盡前剩下的秒數的粗略近似值.連接了交流電源線(POWER_TIME_UNLIMITED).
- power_plugged:True 表明連接了交流電源線.
其他系統信息
-
其他系統信息
psutil.boot_time()
返回自紀元以來以秒錶示的系統啓動時間.In [52]: import psutil,datetime In [53]: psutil.boot_time() Out[53]: 1544831477.0 In [54]:datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M: ...: %S") Out[54]: '2018-12-15 07:51:17'
psutil.users()
將當前在系統上連接的用戶作爲命名元組列表返回,包含:- user: 用戶名稱
- terminal:與用戶關聯的tty或僞tty.
- host: 相關的主機名.
- start: 創建時間爲浮點數,以紀元爲單位,以秒爲單位.
- pid: 登錄過程的PID.
In [56]: psutil.users()
process相關的類
-
process
psutil.pids()
返回當前運行的PID列表。psutil.process_iter(attrs=None,ad_value=None)
返回一個迭代器Process,爲本地計算機上的所有正在運行的進程生成一個類實例。每個實例只創建一次,然後緩存到內部表中,每次生成一個元素時都會更新。Process檢查緩存實例的身份,以便在其他進程重用PID時保證安全.In [59]: import psutil In [60]: for proc in psutil.process_iter(): ...: try: ...: pinfo = proc.as_dict(attrs=['pid','name','username']) ...: except psutil.NoSuchProcess: ...: pass ...: else: ...: print(pinfo) ...: {'name': 'systemd', 'pid': 1, 'username': 'root'} {'name': 'kthreadd', 'pid': 2, 'username': 'root'} {'name': 'kworker/0:0H', 'pid': 4, 'username': 'root'}
使用attrs參數的更緊湊版本: In [62]: for proc in psutil.process_iter(attrs=['pid','name','username']): ...: print(proc.info) 用於創建數據結構的dict: In [63]: procs = {p.pid: p.info for p in psutil.process_iter(attrs=['name','username'])} In [64]: procs 顯示如何按名稱過濾進程: In [66]: [p.info for p in psutil.process_iter(attrs=['pid','name']) if 'python' in p.info['name']]
psutil.pid_exists(pid)
檢查當前進程列表中是否存在給定的PID. 或者: pid in psutil.pids().psutil.wait_procs(procs,timeout = None,callback = None)
等待Process實例列表終止的便捷功能。返回一個元組,指示哪些進程已經消失,哪些進程仍然存在。該走的人都會有一個新的 返回碼屬性,指示進程的退出狀態.終止並等待此進程的所有子進程 import psutil def on_terminate(proc): print("process {} terminated with exit code {}".format(proc, proc.returncode)) procs = psutil.Process().children() for p in procs: p.terminate() gone, alive = psutil.wait_procs(procs, timeout=3, callback=on_terminate) for p in alive: p.kill()
異常的類
-
異常
class psutil.Error
基本異常類。所有其他異常都繼承自此異常.class psutil.NoSuchProcess class psutil.ZombieProcess class psutil.AccessDenied class psutil.TimeoutExpired
進程類
-
進程類
class psutil.Process 表示具有給定pid的OS進程. oneshot() 實用程序上下文管理器.可以顯着加快多個進程信息的檢索速度 In [80]: p = psutil.Process() In [81]: with p.oneshot(): ...: p.name() ...: p.cpu_times() ...: p.cpu_percent() ...: p.create_time() ...: p.ppid() ...: p.status()
oneshot的方法:
cpu_num() cpu_percent() create_time() name() ppid() status() terminal() gids() num_ctx_switches() num_threads() uids() username() memory_full_info() memory_maps()
-
pid:
過程pid,該類的唯一隻讀屬性.
-
ppid()
進程父PID
-
name()
進程名稱
-
exe()
該進程可作爲絕對路徑執行.
In [82]: import psutil In [83]: psutil.Process().exe() Out[83]: '/services/devopsinstall/python3.6/bin/python3.6'
-
cmdline()
此過程的命令行已作爲字符串列表調用
In [85]: psutil.Process().cmdline() Out[85]: ['/services/devopsinstall/python3.6/bin/python3.6', '/services/devopsinstall/python3.6/bin/ipython']
-
environ()
作爲dict的進程的環境變量.
In [87]: psutil.Process().environ()
-
create_time()
流程創建時間爲浮點數. 以UTC爲單位. 以秒爲單位表示.
In [88]: import psutil,datetime In [89]: p = psutil.Process() In [90]: p.create_time() Out[90]: 1544833282.8 In [91]: datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S" ...: ) Out[91]: '2018-12-15 08:21:22'
-
as_dict (attrs=None,ad_value=None)
實用方法將多個流程信息檢索爲字典.
In [92]: import psutil In [93]: p = psutil.Process() In [94]: p.as_dict(attrs=['pid','name','username']) Out[94]: {'name': 'ipython', 'pid': 6296, 'username': 'liyuanjie'}
-
parent()
將父進程作爲Process 對象返回的實用方法,搶先檢查PID是否已被重用.
-
status()
當前進程狀態爲字符串.
-
cwd()
進程當前工作目錄爲絕對路徑.
-
username()
擁有該進程的用戶的名稱.
-
uids()
有效和保存的用戶ID作爲命名元組.
-
gids()
有效和保存的組ID作爲命名元組.
-
terminal()
與此過程關聯的終端.
-
nice
獲取或設置進程的優先級.
In [95]: import psutil In [96]: p = psutil.Process() In [97]: p.nice(10) In [98]: p.nice() Out[98]: 10
-
ionice(inclass=None,value=None)
獲取或設置進程I/O優先級.
In [99]: import psutil In [100]: p = psutil.Process() In [101]: p.ionice(psutil.IOPRIO_CLASS_IDLE) In [102]: p.ionice() Out[102]: pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: 3>, value=0)
-
資源相關的類
-
rlimit()
獲取或設置進程資源限制
In [103]: import psutil In [104]: p = psutil.Process() In [105]: p.rlimit(psutil.RLIMIT_NOFILE,(128,128)) In [106]: p.rlimit(psutil.RLIMIT_FSIZE,(1024,1024)) In [107]: p.rlimit(psutil.RLIMIT_FSIZE) Out[107]: (1024, 1024) In [108]: p Out[108]: psutil.Process(pid=6296, name='ipython', started='08:21:22')
-
io_counters()
將進程I/O統計信息作爲命名元組返回
- read_count:執行的讀取操作數.
- write_count:執行的寫操作次數.
- read_bytes:讀取的字節數
- write_bytes:寫入的字節數.
- read_chars: 此進程傳遞給的字節數read和pread的累積.
- write_chars: 此進程傳遞給的字節數write和pwrite的累積.
In [109]: import psutil In [110]: p = psutil.Process() In [111]: p.io_counters() Out[111]: pio(read_count=58545, write_count=81420, read_bytes=921600, write_bytes=2277 376, read_chars=10377708, write_chars=2828564)
-
num_ctx_switches()
由此過程執行的自願和非自願上下文切換次數.
-
num_fds()
此進程當前打開的文件描述符數
-
num_handles()
此進程當前使用的句柄數.
-
num_threads()
此進程當前使用的線程數.
-
threads()
將進程打開的線程返回爲命名元組列表,包括線程ID和線程CPU時間.
-
cpu_times()
返回一個名爲tuple 的(user,system,children_user,children_system),表示累積的進程時間,以秒爲單位.
-
cpu_percent(interval=None)
返回一個浮點數,表示進程CPU利用率百分比,也可以是進程在不同CPU上運行多個線程的情況。.
In [112]: import psutil In [113]: p = psutil.Process() In [114]: p.cpu_percent(interval=1) Out[114]: 0.0 In [115]: p.cpu_percent(interval=None) Out[115]: 10.0
-
cpu_affinity(cpus=)
獲取或設置進程當前 CPU關聯。CPU親和性包括告訴操作系統僅在一組有限的CPU上運行進程.
In [116]: import psutil In [117]: psutil.cpu_count() Out[117]: 4 In [118]: p = psutil.Process() In [119]: p.cpu_affinity() Out[119]: [0, 1, 2, 3] In [120]: p.cpu_affinity([0,1]) In [121]: p.cpu_affinity() Out[121]: [0, 1] In [122]: p.cpu_affinity([])
-
cpu_num()
返回當前正在運行此進程的CPU.
可結合使用psutil.cpu_percent(percpu=True)來觀察分佈在多個CPU上的系統工作負載. -
memory_info ()
返回具有可變字段的命名元組.
- rss: 進程使用的非交換物理內存.
- vms: 進程使用的虛擬內存總量.
- shared: 與其他進程共享的內存.
- text: 用於可執行代碼的內存量.
- data: 用於可執行代碼以外的物理內存量.
- lib: 共享庫使用的內存.
- dirty: 髒頁的數量.
In [123]: import psutil In [124]: p = psutil.Process() In [125]: p.memory_info() Out[125]: pmem(rss=77422592, vms=2310541312, shared=9818112, text=5578752, lib=0, data =121827328, dirty=0)
-
memory_full_info()
此方法返回相同的信息memory_info().
- uss: 一個進程獨有的內存.表示當前進程終止時將釋放的內存量.
- pss: 是與其他進程共享的內存量.
- swap: 已換出磁盤的內存量.
In [126]: import psutil In [127]: p = psutil.Process() In [128]: p.memory_full_info() Out[128]: pfullmem(rss=77365248, vms=2310541312, shared=9818112, text=5578752, lib=0, data=121827328, dirty=0, uss=72835072, pss=73095168, swap=0)
-
memory_percent(memtype="rss")
將進程內存與總物理系統內存進行比較,並以百分比形式計算進程內存利用率.
-
memory_maps(grouped=True)
將進程的映射內存區域返回爲命名元組的列表,其字段根據平臺而變化.
In [130]: p = psutil.Process() In [131]: p.memory_maps() In [133]: p.memory_maps(grouped=False)
-
children(recursive = False)
將此進程的子節點作爲Process 實例列表返回.
p.children(recursive=True)
-
open_files()
將進程打開的常規文件作爲命名元組列表返回.
- path: 絕對文件路徑
- fd: 文件描述符.
- position: 文件偏移位置.
- mode: 一個表示文件打開方式的字符串.
- flags: 打開文件時傳遞給底層os.open C調用的標誌 .
In [146]: f = open('file.txt','w')
In [147]: p = psutil.Process()
In [148]: p.open_files()
-
connections(kind="inet")
返回由進程打開的套接字連接作爲命名元組的列表.
- fd: 套接字文件描述符.
- family: 地址簇.
- type: 地址類型.
- laddr: 作爲命名元組的本地地址.
- raddr: 作爲命名元組的遠程地址.
- status: 表示TCP連接的狀態.
In [162]: p = psutil.Process(20191) In [163]: p.name() Out[163]: 'firefox' In [164]: p.connections()
-
is_running()
返回當前進程是否在當前進程列表中運行.
-
send_signal()
發送信號進行處理.
-
suspend()
使用SIGSTOP信號暫停進程執行.
-
resume()
使用SIGCONT信號恢復進程執行.
-
terminate()
使用SIGTERM信號終止進程.
-
kill()
使用SIGKILL信號搶佔當前進程.
-
wait()
等待進程終止.
In [165]: p = psutil.Process(20191) In [166]: p.terminate() In [167]: p.wait() In [168]: p Out[168]: psutil.Process(pid=20191, status='terminated')
-
Popen類
-
Popen類
psutil.Popen
In [1]: import psutil In [2]: from subprocess import PIPE In [3]: p = psutil.Popen(["/usr/bin/python3","-c","print('yuanjie')"],stdout=PIPE) In [4]: p.name() Out[4]: 'python3' In [5]: p.username() Out[5]: 'liyuanjie' In [6]: p.communicate() Out[6]: (b'yuanjie\n', None) In [7]: p.wait(timeout=2) Out[7]: 0
psutil.Popen通過with語句支持對象作爲上下文管理器:在退出時,將關閉標準文件描述符,並等待進程.
In [8]: import psutil,subprocess In [9]: with psutil.Popen(["ifconfig"],stdout=subprocess.PIPE) as proc: ...: log.write(proc.stdout.read())
過濾和排序過程
-
過濾和排序過程
這是一個單行的集合,顯示如何使用process_iter()以過濾流程並對其進行排序.
- 查找名稱中包含python的進程
In [12]: import psutil
In [13]: from pprint import pprint as pp
In [14]: pp([p.info for p in psutil.process_iter(attrs=['pid','name']) if 'python' in p.info['name']])
[{'name': 'python3.6', 'pid': 14942},
{'name': 'python3.6', 'pid': 14946},
{'name': 'ipython', 'pid': 22123}]用戶擁有的進程:
In [15]: import getpassIn [16]: pp([(p.pid,p.info['name']) for p in psutil.process_iter(attrs=['name','username']) if p.info['username'] == getpass.getuser()])
[(1751, 'systemd'),
(1752, '(sd-pam)'),
(1765, 'gnome-keyring-daemon'),進程積極運行:
In [17]: pp([(p.pid,p.info) for p in psutil.process_iter(attrs=['name','status']) if p.info['status'] == psutil.STATUS_RUNNING])[(22123, {'name': 'ipython', 'status': 'running'})]
- 查找名稱中包含python的進程
使用日誌文件的進程
- 使用日誌文件的進程:
```
In [18]: import os,psutil
In [20]: for p in psutil.process_iter(attrs=['name','open_files']):
...: for file in p.info['open_files'] or []:
...: if os.path.splitext(file.path)[1] == '.log':
...: print("%-5s %-10s %s" % (p.pid,p.info['name'][:10],file.path))
```
消耗超過500M內存的進程
```
消耗超過500M內存的進程:
In [21]: pp([(p.pid,p.info['name'],p.info['memory_info'].rss) for p in psutil.process_iter(attrs=['name','memory_info']) if p.info['memory_info'].rss > 500 * 1024 * 1024])
消耗最多的3個進程:
In [22]: pp([(p.pid,p.info) for p in sorted(psutil.process_iter(attrs=['name','memory_percent']),key=lambda p: p.info['memory_percent'])][-3:])
```
消耗最多CPU時間的前3個進程
-
消耗最多CPU時間的前3個進程:
In [23]: pp([(p.pid,p.info['name'],sum(p.info['cpu_times'])) for p in sorted(psutil.process_iter(attrs=['name','cpu_times']),key=lambda p: sum(p.info['cpu_times'][:2]))][-3:])
導致I/O最多的前3個進程
-
導致I/O最多的前3個進程
執行錯誤, 報錯: pp([(p.pid, p.info['name']) for p in sorted(psutil.process_iter(attrs=['name', 'io_counters']), key=lambda p: p.info['io_counters'] and p.info['io_counters'][:2])][-3:]) TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
打開更多文件描述符的前3個進程
-
打開更多文件描述符的前3個進程:
pp([(p.pid, p.info) for p in sorted(psutil.process_iter(attrs=['name', 'num_fds']), key=lambda p: p.info['num_fds'])][-3:]) 報錯: TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'