如何获取当前正在执行的Python文件的路径和名称?

560
我有一些脚本调用其他脚本文件,但我需要获取当前正在运行的文件的文件路径。
例如,假设我有三个文件。使用execfile
- `script_1.py` 调用 `script_2.py`。 - `script_2.py` 又调用 `script_3.py`。
在不必从 `script_2.py` 传递该信息作为参数的情况下,我如何从 `script_3.py` 的代码中获取 script_3.py 的文件名和路径?
(执行 `os.getcwd()` 返回的是原始启动脚本的文件路径,而不是当前文件的路径。)

2
os.path.realpath(file) - Girish Gupta
如何正确确定当前脚本目录? - jfs
这个回答是否回答了你的问题?如何正确确定当前脚本目录? - outis
请参阅什么是当前工作目录? - tripleee
26个回答

1
获取执行脚本的目录。
 print os.path.dirname( inspect.getfile(inspect.currentframe()))

0
我编写了一个函数,考虑了Eclipse的调试器和单元测试。它返回您启动的第一个脚本的文件夹。您可以选择指定__file__变量,但主要的是您不必在所有调用层次结构中共享此变量。
也许您可以处理其他我没有看到的堆栈特殊情况,但对我来说这已经足够了。
import inspect, os
def getRootDirectory(_file_=None):
    """
    Get the directory of the root execution file
    Can help: https://dev59.com/T3VD5IYBdhLWcg3wNY1Z
    For eclipse user with unittest or debugger, the function search for the correct folder in the stack
    You can pass __file__ (with 4 underscores) if you want the caller directory
    """
    # If we don't have the __file__ :
    if _file_ is None:
        # We get the last :
        rootFile = inspect.stack()[-1][1]
        folder = os.path.abspath(rootFile)
        # If we use unittest :
        if ("/pysrc" in folder) & ("org.python.pydev" in folder):
            previous = None
            # We search from left to right the case.py :
            for el in inspect.stack():
                currentFile = os.path.abspath(el[1])
                if ("unittest/case.py" in currentFile) | ("org.python.pydev" in currentFile):
                    break
                previous = currentFile
            folder = previous
        # We return the folder :
        return os.path.dirname(folder)
    else:
        # We return the folder according to specified __file__ :
        return os.path.dirname(os.path.realpath(_file_))

0

最简单的方法是:

script_1.py: 中:

import subprocess
subprocess.call(['python3',<path_to_script_2.py>])

script_2.py:

sys.argv[0]

附言:我尝试过使用execfile,但由于它将script_2.py读取为字符串,sys.argv[0]返回了<string>


0
以下代码返回当前主程序所在的路径。我已在Linux、Win10、IPython和Jupyter Lab上进行了测试。我需要一个适用于本地Jupyter笔记本的解决方案。
import builtins
import os
import sys

def current_dir():
    if "get_ipython" in globals() or "get_ipython" in dir(builtins):
        # os.getcwd() is PROBABLY the dir that hosts the active notebook script.
        # See also https://github.com/ipython/ipython/issues/10123
        return os.getcwd()
    else:
        return os.path.abspath(os.path.dirname(sys.argv[0]))

0
我使用了__file__的方法
os.path.abspath(__file__)
但是有一个小技巧,它返回.py文件 当代码第一次运行时, 下一次运行会给出*.pyc文件的名称
所以我选择了:
inspect.getfile(inspect.currentframe())
或者
sys._getframe().f_code.co_filename


0

查找 Python 脚本所在路径的主目录

作为对已有答案的补充(并不回答 OP 的问题,因为其他答案已经解决了这个问题),如果你的脚本路径是 /home/gabriel/GS/dev/eRCaGuy_dotfiles/useful_scripts/cpu_logger.py,而你希望获取该路径的 主目录 部分,即 /home/gabriel,你可以这样做:

import os

# Obtain the home dir of the user in whose home directory this script resides
script_path_list = os.path.normpath(__file__).split(os.sep)
home_dir = os.path.join("/", script_path_list[1], script_path_list[2])

为了帮助理解,这里列出了__file__script_path_listhome_dir的路径。请注意,script_path_list是路径组件的列表,第一个元素为空字符串,因为它最初包含此Linux路径的/根目录路径分隔符:
__file__         = /home/gabriel/GS/dev/eRCaGuy_dotfiles/useful_scripts/cpu_logger.py
script_path_list = ['', 'home', 'gabriel', 'GS', 'dev', 'eRCaGuy_dotfiles', 'useful_scripts', 'cpu_logger.py']
home_dir         = /home/gabriel

源代码:

  1. Python:获取运行脚本所在目录的用户主目录路径[duplicate]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接