注册 登录
编程论坛 Python论坛

求助:__file__的路径显示不同问题

modu 发布于 2019-06-24 10:13, 1646 次点击
今天在写脚本的时候发现一个很奇怪的问题:
我在脚本a中有一段代码如下:
pro_path = os.path.split(os.path.realpath('__file__'))[0]
在a脚本中单独运行,显示pro_path为:
C:\Users\Administrator\Desktop\文档\自动化脚本\myTest\common

b脚本会调用到a脚本,在运行b时,显示pro_path为:
C:\Users\Administrator\Desktop\文档\自动化脚本\myTest
----------------------------------------------------------------------------------
在把上面的代码中'__file__'去掉引号后,两个脚本运行显示:
C:\Users\Administrator\Desktop\文档\自动化脚本\myTest\common

虽然找到了问题原因,但是我不明白加了引号后的'__file__'代码路径会显示不同的路径
2 回复
#2
lwy2xxj2019-06-25 11:11
加上引号,os.path.realpath里面的值是一个字符串,如果不加引号,__file__是当前运行文件的fullname

os.path.realpath的源码如下:

os.path.realpath

Type: <type 'function'>

Value: <function abspath at 0x015D3C70>

Docstring:

"""Return the absolute version of a path."""

Source Code:

    def abspath(path):
        """Return the absolute version of a path."""

        if path: # Empty path must return current working directory.
            try:
                path = _getfullpathname(path)
            except WindowsError:
                pass # Bad path - return unchanged.
        elif isinstance(path, unicode):
            path = os.getcwdu()
        else:
            path = os.getcwd()
        return normpath(path)
#3
modu2019-06-25 17:53
回复 2楼 lwy2xxj
谢谢  搞懂了
1