如何获取当前正在执行的文件的路径和名称? [英] How do I get the path and name of the file that is currently executing?

查看:112
本文介绍了如何获取当前正在执行的文件的路径和名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有调用其他脚本文件的脚本,但是我需要获取进程中当前正在运行的文件的文件路径.

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

例如,假设我有三个文件.使用 execfile :

For example, let's say I have three files. Using execfile:

  • script_1.py调用script_2.py.
  • script_2.py依次调用script_3.py.
  • script_1.py calls script_2.py.
  • In turn, script_2.py calls script_3.py.

如何从script_3.py 中的代码获取 script_3.py 的文件名和路径,而不必将该信息作为script_2.py中的参数传递?

How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py?

(执行os.getcwd()会返回原始启动脚本的文件路径,而不是当前文件的路径.)

(Executing os.getcwd() returns the original starting script's filepath not the current file's.)

推荐答案

p1.py:

execfile("p2.py")

p2.py:

import inspect, os
print (inspect.getfile(inspect.currentframe()) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory

这篇关于如何获取当前正在执行的文件的路径和名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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