[經驗總結] 在 windows 命令窗口中運行 python 腳本時提示 ModuleNotFoundError: No module named 'xxx'


先給出的代碼和目錄結構

獲取CPU代碼如下:

 1 # -*- coding:utf-8 -*-
 2 '''
 3 Created on Sep 10, 2018
 4 
 5 @author: 
 6 '''
 7 import sys
 8 import time
 9 import subprocess
10 from config.getConfig import GetConfigs
11 
12 conf = GetConfigs("config")
13 count = conf.getValue("cpu_times", "count_time")
14 
15 
16 class CPU(object):
17 
18     def __init__(self):
19         self.time = conf.getValue("cpu_times","refresh_time")
20     
21     def read_cpu(self):
22         cpu_info0 = []
23         cpu_info1 = subprocess.check_output('adb shell cat /proc/stat').decode().split()[1:11]
24         for i in cpu_info1:
25             cpu_info0.append(int(i))
26         return cpu_info0
27     
28     def get_idle(self):
29         cpu_idle = self.read_cpu()[3]
30         return cpu_idle
31     
32     def cal_cpu(self):
33         t1_total = sum(self.read_cpu())
34         t1_idle = self.get_idle()
35         time.sleep(self.time)
36         t2_total = sum(self.read_cpu())
37         t2_idle = self.get_idle()
38         cpu_usage = (1 - (t2_idle - t1_idle)/(t2_total - t1_total))*100
39         if cpu_usage < 0:
40 #                 print (time.strftime('%Y-%m-%d %H:%M:%S') + " The CPU usage is %d" %(0,) + "%")
41             return cpu_usage == 0
42         else:
43 #                 print (time.strftime('%Y-%m-%d %H:%M:%S') + " The CPU usage is %d" %cpu_usage + "%")
44             return str(int(cpu_usage))
45             
46 if __name__ == "__main__":
47         cpu_collection = CPU()
48         for i in range(count):
49             with open("cpu.txt","a") as f:
50                 f.write(cpu_collection.cal_cpu() + '\n')
51             print (cpu_collection.cal_cpu())
52             
View Code

 

獲取配置文件代碼如下:

 1 # -*- coding:utf-8 -*-
 2 '''
 3 Created on Nov 1, 2018
 4 
 5 @author: 
 6 
 7 Comment: 
 8 '''
 9 import os
10 import sys
11 import time
12 from configparser import ConfigParser
13 
14 class GetConfigs(object):
15     def __init__(self,filename):
16         self.filename =filename
17     
18     def getValue(self,section,option):
19         """
20         @file: string,the name of the config file
21         @section: string,the name of the section in config file
22         @option: string,the name of the option in section field
23         This function will return a int value which the option is specified.
24         """
25         try:
26             configs = ConfigParser()
27             filepath = sys.path[1] + "\\config\\" + self.filename + ".ini" 
28             line = configs.read(filepath)
29             result = configs.getint(section, option)
30             return int(result)
31         except Exception as e:
32             print (e)
View Code

 

代碼目錄結構:

 

在IDE里面直接執行 cpu.py文件是正常的,正常輸出 CPU 信息,但放到命令窗口執行卻提示 config 模塊不存在

1、打開運行窗口輸入 cmd進入命令窗口

2、切換至代碼所在目錄:d:     --> cd D:\WorkSpace3\performance\cpu

3、運行 python3 cpu.py

 

分析:

提示自定義的模塊不存在時,一般都是路徑獲取不正確導致未正常找到相應的模塊,順應這個思路看看哪些代碼中涉及到模塊路徑

1、首先在 cpu.py文件中我們有開始去嘗試 import config 這個包,需要先對這個進行確認是否正常找到的 config這個路徑

2、我們在cpu.py代碼中新增一行 print (sys.path),把路徑全部打印出來確認,從下圖中的輸出來看,根本就沒有到performance這一層目錄,這樣就肯定會找不到下一級的 config 目錄,所以就報找不到該模塊

 

 

 解決方法

要讓程序能正常找到相應目錄,勢必要通過外部的手段將該路徑添加進去,首先想到的就是添加環境變量,只要是環境變量中有配置對應的 path ,在命令窗口運行的程序都會到相應的 path中一一去查找,直到找到為止,可以添加到系統原生的path里面,為有利於區分,額外添加一個 PYTHONPATH 的環境變量,將其它需要手動添加的路徑全部放到該環境變量里面,添加的原則是,要導入哪個包,只要將該包的上一層路徑全部添加至環境變量中。比如我這里 config 包是在 performance這一層目錄,所以我就只將到Performance這絕對目錄添加到 PYTHONPATH環境變量即可,如下圖:

 

 添加完成之后,重新打開命令窗口,進入到代碼所在路徑重新執行,代碼執行正常,CPU信息也正常顯示出來。

 

 

答疑

有人會問是什么原因導致了 這個問題,按正常理解來說在IDE里面能運行,在命令窗口里也照樣能運行,都是執行的同一份文件?

       這是因為Python在啟動解釋器(Interpreter)的時候不只會導入環境變量中sys.path發現的模塊,還會導入當前工作目錄下的模塊。當你在IDLE中啟動解釋器時,當前的工作目錄就是項目目錄,能順利調用同項目中的模塊;但是當你通過命令行啟動時,當前工作目錄為你啟動解釋器時所在的目錄(即C盤的安裝目錄),如果當時的位置不是項目目錄,那么項目目錄中的模塊就不會被找到。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM