从另一个文件导入变量-防止导入文件中的代码

时间:2019-10-29 17:51:18

标签: python

我想从a.py导入archivepath变量

文件b.py:

import os
from a import archivepath
from os.path import dirname, abspath

文件a.py:

def getPath():
    try:
        # Open the key and return the handle object.
        hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
               "SOFTWARE\\COMODO")
            # Read the value.                      
        result = _winreg.QueryValueEx(hKey, "MachineId)
        # Close the handle object.
        result = result[0]
        return result
        _winreg.CloseKey(hKey)
    except Exception, e:
        print str(e)
archive = "C:\path\Archive" 

ID = "94"



path = getPath()

Dir = os.path.join(path,“ state”,ID)

运行b.py时获取:

[Error 2] The system cannot find the file specified
Traceback (most recent call last):
  File "b.py", line 16, in <module>
    from a import archivepath
  File "C:\Users\user\Downloads\\a.py", line 77, >in <module>
    Dir = os.path.join(path, "state", ID)
  File "C:\Python27\lib\ntpath.py", line 65, in join
    result_drive, result_path = splitdrive(path)
  File "C:\Python27\lib\ntpath.py", line 115, in splitdrive
    if len(p) > 1:
TypeError: object of type 'NoneType' has no len()

当我删除Dir行时,没有错误。

我在b.py中尝试过:

import os
 from a import archivepath
 from os.path import dirname, abspath

if __name__ == '__main__':
    Dir = os.path.join(path, "state", ID)

但是出现相同的错误。

如何在导入a.py时防止执行Dir行?

1 个答案:

答案 0 :(得分:1)

您是否检查过从function runningTime(arr) { var count=0; var temp; for(var i=1 ; i<arr.length; i++){ for(var j=0 ; j<i; j++){ if(arr[j]>arr[i]){ temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; count++; } } } return count; } console.log(runningTime([4, 4, 3, 4]));获得了预期的结果?它返回getPath(),因为在None子句中,您只是在打印异常而没有返回任何内容。以后每次使用except都会使用path而不是所需的返回值。

此外,None执行from a import archivepath,该命令无法正常工作,因此无法导入所需的内容。修复a.py将成功导入getPath()。另外,如果您不想在导入时为archivepath执行getPath(),可以像这样修改posDir

a.py