【问题标题】:A function that imports modules depending on the operating system根据操作系统导入模块的函数
【发布时间】:2021-03-20 16:41:41
【问题描述】:

我编写了一个脚本,它应该在不同的操作系统上运行:我朋友的计算机和大学的服务器。大学的服务器是Linux,所以我无法安装的模块很少,因为我没有sudo权限。 (旁注:我的主脚本中调用这些模块的部分(仅后处理部分,而不是运行计算的部分)为 Linux 进行了注释)。为此,我创建了一个名为“functions.py”的 python 文件,其中定义了我的所有函数,并且还使用了要在主文件中导入的模块的条件导入,如下所示:

def import_function_(Use_multiprocessing):

    import platform, cmath, math, os, shutil, subprocess as s

    if Use_multiprocessing:
        if platform.system()=='Linux':
            from multiprocessing import Process
            print("Your machine has "+platform.system()+" as an operating system, you can use threading by activating the variable Use_multiprocessing ")
        elif platform.system()!='Linux':
            import matlab.engine, numpy as n, ltspice
            from colorama import Fore, init
            init(autoreset=True)
            print(Fore.RED+"Your machine has "+platform.system()+" as an operating system, no threading can be used, sorry...")
    if __name__ != 'main':
        import functions as fct

但是,当我运行主文件时,即使我正在导入上面的函数,我也会收到诸如“os 未定义,numpy 未定义...”和所有先前导入的模块之类的错误...

我做错了什么?

【问题讨论】:

    标签: python import operating-system


    【解决方案1】:

    这些库没有定义,因为它们只在函数内部被提及,而不是在模块级别。 我建议如下:

    import_modules.py

    import platform
    import cmath
    import math
    import os
    import shutil
    import subprocess as s
    
    if platform.system() == 'Linux':
        from multiprocessing import Process
    
        print(
            "Your machine has " + platform.system() + " as an operating system, you can use threading by activating the variable Use_multiprocessing ")
    elif platform.system() != 'Linux':
        import numpy as n
        from colorama import Fore, init
    
        init(autoreset=True)
        print(
            Fore.RED + "Your machine has " + platform.system() + " as an operating system, no threading can be used, sorry...")
    

    main.py

    from import_modules import *
    

    如果确实需要分离多处理部分,请将其放入另一个文件(import_modules_mp.py),如果“Use_multiprocessing”为True,则导入该文件。

    PS:不过,在需要特定库的模块中导入库会被认为是更好的做法。不要担心性能。导入的库将被缓存。因此,导入过程不会执行多次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2014-12-22
      • 2023-03-27
      • 2016-04-15
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多