zoukankan      html  css  js  c++  java
  • [经验总结] 在 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() + '
    ')
    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:WorkSpace3performancecpu

    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盘的安装目录),如果当时的位置不是项目目录,那么项目目录中的模块就不会被找到。

  • 相关阅读:
    养生之《爱的供养》
    道家养生,与佛家养德
    个人的佛法·5·活着,与死去
    自我囚禁与安住于轮回
    个人的佛法·4·我是不是东西?
    个人的佛法·2
    我们都是生命的灯塔
    大O表示法是什么?
    uni-app商城项目(01)
    2059
  • 原文地址:https://www.cnblogs.com/aziji/p/9896387.html
Copyright © 2011-2022 走看看