简体   繁体   English

Python:如何获取导入模块中文件的绝对路径

[英]Python: How to get absolute path of file in imported module

I have imported a module as: 我已将模块导入为:

from source.x.ReviseOnOrder import reviseOnX, x

The method reviseOnX runs another python script, say y.py which is in the same location ie /source/x . reviseOnX方法运行另一个python脚本,即y.py ,它位于同一位置,即/source/x So, when executing reviseOnX , I'd like to know the full path so that I can pass the correct path to subprocess that calls y.py . 因此,在执行reviseOnX ,我想知道完整路径,以便可以将正确的路径传递给调用y.pyy.py

Based on other SO questions, I tried the following: 基于其他SO问题,我尝试了以下操作:

print os.path(source.x.ReviseOnOrder.__file__)

But it gives the following error: 但是它给出了以下错误:

NameError: global name 'source' is not defined

How can I find the correct path? 如何找到正确的路径?

You only have references to objects imported from the module, you don't have the module object itself. 您仅具有对从模块导入的对象的引用,而没有模块对象本身。

Use the inspect.getmodule() function to get the module object again: 使用inspect.getmodule()函数再次获取模块对象:

import inspect

mod = inspect.getmodule(reviseOnX)
print os.path.abspath(mod.__file__)

Note that I am using os.path.abspath() , not os.path() . 请注意,我使用的是os.path.abspath()而不是 os.path() The latter would try to call the module. 后者将尝试调用该模块。

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

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