python - How to get object from file that imported another file?
问题描述
Say I have a python file called fileOne.py
that imports fileTwo.py
. Is there a way for fileTwo.py
to access the objects from fileOne.py
dynamically? So fileTwo.py
doesn't need to know the name of the file that will import it, and instead can do something like this: FILE_THAT_IMPORTED_ME.myFunction()
.
Basically I want to know if there is a way to access objects from the 'parent' file that is importing a script, from said script.
解决方案
You can access the file which imported you by doing import __main__
and __main__
will contain the parent module.
a.py#
import b
print(b)
b.py#
import __main__
print(__main__)
Executing a.py
will result in
<module '__main__' from '/home/jonatan/PycharmProjects/tests/test/a.py'>
<module 'b' from '/home/jonatan/PycharmProjects/tests/test/b.py'>
Note that __main__
is being printed before b
since the module b has to complete its loading before continue the file a
.
推荐阅读
- go - Should I checkin pkg/mod/cache to git?
- expo - 世博会客户端安装:sill doserial remove 14516
- xcode - 如何修复 Xcode 编译器?
- go - 如何使用 gRPC 服务器流检测 Cloud Run 中取消/丢失/关闭的连接?
- terminal - 用于在终端中调整 ANSI 颜色代码的“示例”文件
- c# - 使用 C# 从 HTML5 下拉列表中获取用户选择的值
- ray - Ray rllib 自定义训练流程
- java - 无法创建新会话。(原始错误:命令失败:...\adb.exe -s 192.168.150.105:5555 shell "ps 'uiautomator'"" ps: uiautomator)
- powershell - Powershell 转义字符嵌套量词
- reactjs - React Firebase Axios:将数据保存到 Firebase 的问题