在python中,如果一个模块调用另一个模块的功能,该功能是否可以访问第一个模块的文件路径? [英] In python, if a module calls upon another module's functions, is it possible for the function to access the first module's filepath?

查看:92
本文介绍了在python中,如果一个模块调用另一个模块的功能,该功能是否可以访问第一个模块的文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有将其作为参数传递...

Without passing it as a parameter...

例如在test1.py中:

Ex. In test1.py:

def function():
    print (?????)

和在test2.py

and in test2.py

import test1

test1.function()

有可能写?????所以运行test2.py会打印出"test2.py"或完整的文件路径? __ 文件 __ 将打印出"test1.py".

Is it possible to write ????? so running test2.py prints out 'test2.py' or the full filepath? __file__ would print out 'test1.py'.

推荐答案

可以使用 test2.py看起来很像您的,但已修复import:

test2.py looks much like yours but with the the import fixed:

% cat test2.py
#!/usr/bin/env python

import test1

test1.function()

试运行...

% ./test2.py 
Called from within: ./test2.py

N.B:

CPython实现细节:此函数应仅用于内部目的和专用目的.不能保证它在所有Python实现中都存在.

CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.

这篇关于在python中,如果一个模块调用另一个模块的功能,该功能是否可以访问第一个模块的文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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