从父目录导入脚本 [英] Import Script from a Parent Directory

查看:75
本文介绍了从父目录导入脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何导入位于父目录中的模块(python文件)?



两个目录都有 __ init __。py 文件,但我仍然无法从父目录导入文件?



在此文件夹布局中,脚本B正在尝试导入脚本A:

 文件夹A:
__init__.py
脚本A:
文件夹B:
__init__.py
脚本B(尝试导入脚本A)

以下代码脚本B不起作用:

  import ../scriptA.py#我收到编译错误,说。无效


解决方案

您不用Python导入脚本导入模块。一些python模块也是可以直接运行的脚本(它们在模块级别执行一些有用的工作)。



一般来说,最好使用绝对导入而不是相对进口。

  toplevel_package / $ b $b├──__init__.py $ b $b├──moduerA.py$ b $b└──子包装$ b $b├──__init__.py$ b $b└──moduleB.py


$从$ to $ $

如果你想运行 moduleB.py 作为脚本,然后确保 toplevel_package 的父目录位于 sys.path 中。


How do I import a module(python file) that resides in the parent directory?

Both directories have a __init__.py file in them but I still cannot import a file from the parent directory?

In this folder layout, Script B is attempting to import Script A:

Folder A:
   __init__.py
   Script A:
   Folder B:
     __init__.py
     Script B(attempting to import Script A)

The following code in Script B doesn't work:

import ../scriptA.py # I get a compile error saying the "." is invalid

解决方案

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
├── __init__.py
├── moduleA.py
└── subpackage
    ├── __init__.py
    └── moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

这篇关于从父目录导入脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆