Python script self name

Get the path of the currently executing python script using import. (Python recipe) by Jitender Cheema

William B. good one, understood.How to do in Windows ??

Why not use sys.path[0] ? Statement ‘print sys.path[0]’ does what you want, see http://docs.python.org/lib/module-sys.html

addition: full path to running script. Well, to get the path + script file do something like: ‘print os.path.join(sys.path[0], sys.argv[0])’

As I said there can be many ways, one of the way is using: sys.path[0] sys.path is List of paths.. Try this in python interpreter import sys print sys.path # prints out a whole list of python module paths.. print sys.path[0] # prints out » Now try same as a python script and compare: import sys print sys.path # prints out a whole list of python module paths.. print sys.path[0] # prints out cwd

The current directory can be interpreted more than one way. In order to understand what is going on with the following short section of code, put it in a file named pwd.py, then do the following:

mkdir junk cd junk python ../pwd.py 

You need to make sure that your current working directory (the cd command destination) is not the same as the directory containing the Python script. After that it is self explanatory except for the .EXE path. Try running the script through PY2EXE first, and this will make more sense.

import os,sys print "CWD: ",os.getcwd() print "Script: ",sys.argv[0] print ".EXE: ",os.path.dirname(sys.executable) print "Script dir: ", os.path.realpath(os.path.dirname(sys.argv[0])) pathname, scriptname = os.path.split(sys.argv[0]) print "Relative script dir: ",pathname print "Script dir: ", os.path.abspath(pathname) 

sys.path[0] is not the same. Here’s my (slightly) cleaned up version:

import sys import os, os.path def get_my_path(): import fake path = str(fake).split()[3][1:-9] os.remove( os.path.join( path, 'fake.pyc' ) ) return path def do(): print "sys.path[0]: %s" % sys.path[0] print "os.getcwd(): %s" % os.getcwd() print "get_my_path(): %s" % get_my_path()

Import this module from a different directory (make sure it’s in your PYTHONPATH) and invoke do(). You’ll see that the first two paths are the directory you’re invoking from, but the third is the directory containing the module.

Thanks to all for your inputs.

Just summarizing what worked best for me (I needed to get the path of the current module). It was tested on both Linux and Windows, with all the usages I could think of.

os.path.dirname( os.path.realpath( __file__ ) ) 

The reason for the additionnal call to os.path.realpath() is that omitting it will only work if you run the script by specifying its full path (or, under Windows, if you only type the python script name — this is because Windows has Python.exe associated to that extension and will specify the full path of the script whenever it invokes it).

Читайте также:  Byte literal contains python

So, to import from a location relative to the current path, you can do:

import os # BASE_PATH is the absolute path of ../.. relative to this script location BASE_PATH = reduce (lambda l,r: l + os.path.sep + r, os.path.dirname( os.path.realpath( __file__ ) ).split( os.path.sep )[:-2] ) # add ../../scripts (relative to the file (!) and not to the CWD) sys.path.append( os.path.join( BASE_PATH, "scripts" ) ) import foobar if __name__ == '__main__': . 

i get the same path info for either BASE_PATH. very clever idea — would like to make it work. if you can, please see if i missed soemthing? i created a folder one level up names scripts, and put a module in there names foo.py foo.py is just a hello world. the error is no module foo found. tia, greg

!/usr/bin/python

import os from os import path import sys

BASE_PATH is the absolute path of ../.. relative to this script location

BASE_PATH = reduce (lambda l,r: l + os.path.sep + r, os.path.dirname( os.path.realpath( __file__ ) ).split( os.path.sep )[:-2] )

print BASE_PATH, ‘original base path’

add ../../scripts (relative to the file (!) and not to the CWD)

sys.path.append( os.path.join( BASE_PATH, «../scripts/» ) )

print BASE_PATH, ‘modified base path’

Источник

Get name of current script in Python

You can use __file__ to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked.

If you want to omit the directory part (which might be present), you can use os.path.basename(__file__) .

For completeness’ sake, I thought it would be worthwhile summarizing the various possible outcomes and supplying references for the exact behaviour of each.

The answer is composed of four sections:

  1. A list of different approaches that return the full path to the currently executing script.
  2. A caveat regarding handling of relative paths.
  3. A recommendation regarding handling of symbolic links.
  4. An account of a few methods that could be used to extract the actual file name, with or without its suffix, from the full file path.
Читайте также:  Updating python interpreter pycharm

Extracting the full file path

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’ . If no script name was passed to the Python interpreter, argv[0] is the empty string.

import inspect source_file_path = inspect.getfile(inspect.currentframe()) 
import lib_programname # this returns the fully resolved path to the launched python program path_to_program = lib_programname.get_path_executed_script() # type: pathlib.Path 

Handling relative paths

When dealing with an approach that happens to return a relative path, it might be tempting to invoke various path manipulation functions, such as os.path.abspath(. ) or os.path.realpath(. ) in order to extract the full or real path.

However, these methods rely on the current path in order to derive the full path. Thus, if a program first changes the current working directory, for example via os.chdir(. ) , and only then invokes these methods, they would return an incorrect path.

If the current script is a symbolic link, then all of the above would return the path of the symbolic link rather than the path of the real file and os.path.realpath(. ) should be invoked in order to extract the latter.

Further manipulations that extract the actual file name

os.path.basename(. ) may be invoked on any of the above in order to extract the actual file name and os.path.splitext(. ) may be invoked on the actual file name in order to truncate its suffix, as in os.path.splitext(os.path.basename(. )) .

From Python 3.4 onwards, per PEP 428, the PurePath class of the pathlib module may be used as well on any of the above. Specifically, pathlib.PurePath(. ).name extracts the actual file name and pathlib.PurePath(. ).stem extracts the actual file name without its suffix.

This will print foo.py for python foo.py , dir/foo.py for python dir/foo.py , etc. It’s the first argument to python . (Note that after py2exe it would be foo.exe .)

Источник

Python script self name

Запись: and-semakin/mytetra_data/master/base/1588747838xm8yfxb152/text.html на raw.githubusercontent.com

Если нужно получить путь к текущему выполняемому скрипту, то можно прочитать значение из специальной переменной __file__ (она не определена в REPL, только в скриптах, которые запускаются из файлов).

Читайте также:  Как настроить css кнопки

Вот так можно получить абсолютный путь к выполняемому скрипту:

Если нужно получить имя главного модуля программы, то можно __file__ заменить на __main__.__file__ .

  • Закодировать файл в base64 на Python
  • Рекурсивное создание директорий в Python
  • Сортировка в Python
  • Правильно добавить год/месяц к дате в Python
  • Отформатировать дату в Python
  • Получить рабочую директорию и директорию со скриптом в Python
  • Копия объекта в Python
  • Время выполнения программы на Python
  • Конвертировать datetime.timedelta в строку
  • Парсинг даты в Python
  • Конвертировать строку (str) в булевый тип (bool) в Python
  • Получить местный часовой пояс в Python
  • Проверить, что строка соответствует регулярному выражению в Python
  • Просмотреть доступные версии модулей в PIP
  • Получить целочисленный Unix timestamp в Python
  • getter и setter в Python
  • Настроить формат вывода логов в Python
  • Получить переменную окружения в Python
  • Обновить пакет в PIP
  • Получить имя (хостнейм) машины из Python
  • Вывести стэк вызовов при возникновении исключения в Python
  • Функция eval в Python
  • Дозаписывать (append) в файл в Python
  • Препроцессинг кода в Python
  • Проверить, что программа установлена из Python
  • Настроить путь для импорта библиотек в Python
  • Получить размер терминала в символах в Python
  • Enum с дополнительными полями в Python
  • Ошибка invalid command ‘bdist_wheel’ при установке пакета через PIP
  • Получить список аргументов функции из Python
  • Сделать словарь только для чтения в Python
  • Заматчить любой символ, включая перевод строки, в регулярных выражениях на Python
  • Получить список файлов в директории через pathlib в Python
  • Вывести действительное число с округлением до нескольких символов после запятой в Python
  • Вывод в терминал текста с цветами в Python
  • Перезагрузить импортированный модуль в Python
  • Безопасно создать список/словарь/любой объект из строкового представления в Python
  • Аналог декоратора @property для методов класса в Python
  • Перехватить ошибку TimeoutError в asyncio
  • Отключить вывод логов в Python
  • Уровни логгирования в Python
  • Удалить *.pyc и __pycache__ файлы
  • Выгрузить объект в JSON в Unicode в Python
  • Конвертировать datetime в другую часовую зону в Python
  • Дополнить строку нулями в Python
  • Вычислить MD5 от строки в Python
  • Удалить знаки пунктуации из строки в Python
  • Проверить, что первая буква в строке — заглавная, в Python
  • Разбить (split) строку по нескольким разделителям в Python
  • Отсортировать версии в Python
  • Распаковать любой архив в Python
  • Получить имя текущего скрипта на Python
  • Установка pip на Python 2.6
  • Отличить печатаемый символ Unicode от непечатаемого на Python
  • Вывести версию интерпретатора Python в машиночитаемом виде
  • Найти место, куда Python устанавливает пакеты (dist-packages, site-packages)

Источник

Оцените статью