简体   繁体   English

如何从 python 中的 __main__ 导入相关模块

[英]How to import relative module from __main__ in python

I have two file我有两个文件

foo.py
main.py

while executing python main.py , I want main.py to import foo.py .在执行python main.py ,我希望main.py导入foo.py

I tried我试过了

from . import foo

But python complains但是 python 抱怨

Attempted relative import beyond top-level package

I also tried我也试过

from foo import func_name

It works, but that means I can only directly import what get exposed.它有效,但这意味着我只能直接导入暴露的内容。 I want to use it like foo.func_name我想像foo.func_name一样使用它

Is it possible to import the whole module in a relative way (regardless what the current working directory is)?是否可以以相对方式导入整个模块(不管当前工作目录是什么)?

The script directory is already a part of the import path.脚本目录已经是导入路径的一部分。 Simply use只需使用

import foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM