¿Cómo obtener el nombre de archivo del módulo principal en Python?
Supongamos que tengo dos módulos:
A.py:
import b
print __name__, __file__
B.py:
print __name__, __file__
Corro el "a.py" archivo. Esto imprime:
b C:\path\to\code\b.py
__main__ C:\path\to\code\a.py
Pregunta: ¿cómo obtengo la ruta al módulo __main__
("a.py" en este caso) desde dentro de la "b.py" ¿biblioteca?
5 answers
import __main__
print __main__.__file__
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-03 16:04:22
Tal vez esto haga el truco:
import sys
from os import path
print path.abspath(sys.modules['__main__'].__file__)
Tenga en cuenta que, por seguridad, debe verificar si el módulo __main__
tiene un atributo __file__
. Si se crea dinámicamente, o simplemente se está ejecutando en la consola interactiva de python, no tendrá un __file__
:
python
>>> import sys
>>> print sys.modules['__main__']
<module '__main__' (built-in)>
>>> print sys.modules['__main__'].__file__
AttributeError: 'module' object has no attribute '__file__'
Una simple comprobación de hasattr() hará el truco para evitar el escenario 2 si esa es una posibilidad en tu aplicación.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-03 18:39:58
El código python a continuación proporciona funcionalidad adicional, incluyendo que funciona a la perfección con py2exe
ejecutables.
Utilizo código similar a este para encontrar rutas relativas al script en ejecución, también conocido como __main__
. como beneficio adicional, funciona multiplataforma, incluyendo Windows.
import imp
import os
import sys
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old py2exe
or imp.is_frozen("__main__")) # tools/freeze
def get_main_dir():
if main_is_frozen():
# print 'Running from path', os.path.dirname(sys.executable)
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
# find path to where we are running
path_to_script=get_main_dir()
# OPTIONAL:
# add the sibling 'lib' dir to our module search path
lib_path = os.path.join(get_main_dir(), os.path.pardir, 'lib')
sys.path.insert(0, lib_path)
# OPTIONAL:
# use info to find relative data files in 'data' subdir
datafile1 = os.path.join(get_main_dir(), 'data', 'file1')
Esperemos que el código de ejemplo anterior pueda proporcionar información adicional sobre cómo determinar la ruta al script en ejecución...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-03 20:29:30
Otro método sería usar sys.argv[0]
.
import os
import sys
main_file = os.path.realpath(sys.argv[0]) if sys.argv[0] else None
sys.argv[0]
será una cadena vacía si Python se inicia con -c
o si se comprueba desde la consola de Python.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-05 18:16:14
import sys, os
def getExecPath():
try:
sFile = os.path.abspath(sys.modules['__main__'].__file__)
except:
sFile = sys.executable
return os.path.dirname(sFile)
Esta función funcionará para programas compilados en Python y Cython.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-17 21:17:50