[经验总结] 在 windows 命令窗口中运行 python 脚本时提示 ModuleNotFoundError: No module named 'xxx'

先给出的代码和目录结构

获取CPU代码如下:

 # -*- coding:utf-8 -*-
'''
Created on Sep 10, 2018 @author:
'''
import sys
import time
import subprocess
from config.getConfig import GetConfigs conf = GetConfigs("config")
count = conf.getValue("cpu_times", "count_time") class CPU(object): def __init__(self):
self.time = conf.getValue("cpu_times","refresh_time") def read_cpu(self):
cpu_info0 = []
cpu_info1 = subprocess.check_output('adb shell cat /proc/stat').decode().split()[1:11]
for i in cpu_info1:
cpu_info0.append(int(i))
return cpu_info0 def get_idle(self):
cpu_idle = self.read_cpu()[3]
return cpu_idle def cal_cpu(self):
t1_total = sum(self.read_cpu())
t1_idle = self.get_idle()
time.sleep(self.time)
t2_total = sum(self.read_cpu())
t2_idle = self.get_idle()
cpu_usage = (1 - (t2_idle - t1_idle)/(t2_total - t1_total))*100
if cpu_usage < 0:
# print (time.strftime('%Y-%m-%d %H:%M:%S') + " The CPU usage is %d" %(0,) + "%")
return cpu_usage == 0
else:
# print (time.strftime('%Y-%m-%d %H:%M:%S') + " The CPU usage is %d" %cpu_usage + "%")
return str(int(cpu_usage)) if __name__ == "__main__":
cpu_collection = CPU()
for i in range(count):
with open("cpu.txt","a") as f:
f.write(cpu_collection.cal_cpu() + '\n')
print (cpu_collection.cal_cpu())

获取配置文件代码如下:

 # -*- coding:utf-8 -*-
'''
Created on Nov 1, 2018 @author: Comment:
'''
import os
import sys
import time
from configparser import ConfigParser class GetConfigs(object):
def __init__(self,filename):
self.filename =filename def getValue(self,section,option):
"""
@file: string,the name of the config file
@section: string,the name of the section in config file
@option: string,the name of the option in section field
This function will return a int value which the option is specified.
"""
try:
configs = ConfigParser()
filepath = sys.path[1] + "\\config\\" + self.filename + ".ini"
line = configs.read(filepath)
result = configs.getint(section, option)
return int(result)
except Exception as e:
print (e)

代码目录结构:

[经验总结] 在 windows 命令窗口中运行 python 脚本时提示 ModuleNotFoundError: No module named 'xxx'

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

1、打开运行窗口输入 cmd进入命令窗口

2、切换至代码所在目录:d:     --> cd D:\WorkSpace3\performance\cpu

3、运行 python3 cpu.py

[经验总结] 在 windows 命令窗口中运行 python 脚本时提示 ModuleNotFoundError: No module named 'xxx'

分析:

提示自定义的模块不存在时,一般都是路径获取不正确导致未正常找到相应的模块,顺应这个思路看看哪些代码中涉及到模块路径

1、首先在 cpu.py文件中我们有开始去尝试 import config 这个包,需要先对这个进行确认是否正常找到的 config这个路径

2、我们在cpu.py代码中新增一行 print (sys.path),把路径全部打印出来确认,从下图中的输出来看,根本就没有到performance这一层目录,这样就肯定会找不到下一级的 config 目录,所以就报找不到该模块

[经验总结] 在 windows 命令窗口中运行 python 脚本时提示 ModuleNotFoundError: No module named 'xxx'

解决方法

要让程序能正常找到相应目录,势必要通过外部的手段将该路径添加进去,首先想到的就是添加环境变量,只要是环境变量中有配置对应的 path ,在命令窗口运行的程序都会到相应的 path中一一去查找,直到找到为止,可以添加到系统原生的path里面,为有利于区分,额外添加一个 PYTHONPATH 的环境变量,将其它需要手动添加的路径全部放到该环境变量里面,添加的原则是,要导入哪个包,只要将该包的上一层路径全部添加至环境变量中。比如我这里 config 包是在 performance这一层目录,所以我就只将到Performance这绝对目录添加到 PYTHONPATH环境变量即可,如下图:

[经验总结] 在 windows 命令窗口中运行 python 脚本时提示 ModuleNotFoundError: No module named 'xxx'

添加完成之后,重新打开命令窗口,进入到代码所在路径重新执行,代码执行正常,CPU信息也正常显示出来。

[经验总结] 在 windows 命令窗口中运行 python 脚本时提示 ModuleNotFoundError: No module named 'xxx'

答疑

有人会问是什么原因导致了 这个问题,按正常理解来说在IDE里面能运行,在命令窗口里也照样能运行,都是执行的同一份文件?

这是因为Python在启动解释器(Interpreter)的时候不只会导入环境变量中sys.path发现的模块,还会导入当前工作目录下的模块。当你在IDLE中启动解释器时,当前的工作目录就是项目目录,能顺利调用同项目中的模块;但是当你通过命令行启动时,当前工作目录为你启动解释器时所在的目录(即C盘的安装目录),如果当时的位置不是项目目录,那么项目目录中的模块就不会被找到。

上一篇:《Java EE核心框架实战》—— 2.2 连接DB数据库的参数来自于Properties对象


下一篇:SpringBoot开发案例之配置阿里巴巴Druid连接池