Print script name python

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__) .

Similar question

Since the OP asked for the name of the current script file I would prefer

import os os.path.split(sys.argv[0])[1] 

all that answers are great, but have some problems You might not see at the first glance.

lets define what we want — we want the name of the script that was executed, not the name of the current module — so __file__ will only work if it is used in the executed script, not in an imported module. sys.argv is also questionable — what if your program was called by pytest ? or pydoc runner ? or if it was called by uwsgi ?

and — there is a third method of getting the script name, I havent seen in the answers — You can inspect the stack.

Another problem is, that You (or some other program) can tamper around with sys.argv and __main__.__file__ — it might be present, it might be not. It might be valid, or not. At least You can check if the script (the desired result) exists !

the library lib_programname does exactly that :

  • check if __main__ is present
  • check if __main__.__file__ is present
  • does give __main__.__file__ a valid result (does that script exist ?)
  • if not: check sys.argv:
  • is there pytest, docrunner, etc in the sys.argv ? —> if yes, ignore that
  • can we get a valid result here ?
  • if not: inspect the stack and get the result from there possibly
  • if also the stack does not give a valid result, then throw an Exception.

by that way, my solution is working so far with setup.py test , uwsgi , pytest , pycharm pytest , pycharm docrunner (doctest) , dreampie , eclipse

there is also a nice blog article about that problem from Dough Hellman, «Determining the Name of a Process from Python»

BTW, it will change again in python 3.9 : the file attribute of the main module became an absolute path, rather than a relative path. These paths now remain valid after the current directory is changed by os.chdir()

Читайте также:  Error no main class specified kotlin

So I rather want to take care of one small module, instead of skimming my codebase if it should be changed somewere .

Disclaimer: I’m the author of the lib_programname library.

bitranox 1368

You can do this without importing os or other libs.

If you want to get the path of current python script, use: __file__

If you want to get only the filename without .py extension, use this:

we can try this to get current script name without extension.

import os script_name = os.path.splitext(os.path.basename(__file__))[0] 

Krishn Singh 61

As of Python 3.5 you can simply do:

from pathlib import Path Path(__file__).stem 

For example, I have a file under my user directory named test.py with this inside:

from pathlib import Path print(Path(__file__).stem) print(__file__) 
>>> python3.6 test.py test test.py 

elad silver 8529

If you’re doing an unusual import (e.g., it’s an options file), try:

import inspect print (inspect.getfile(inspect.currentframe())) 

Note that this will return the absolute path to the file.

Gajendra D Ambi 3418

ceth 42790

For modern Python versions (3.4+), Path(__file__).name should be more idiomatic. Also, Path(__file__).stem gives you the script name without the .py extension.

The Above answers are good . But I found this method more efficient using above results.
This results in actual script file name not a path.

import sys import os file_name = os.path.basename(sys.argv[0]) 

Note that __file__ will give the file where this code resides, which can be imported and different from the main file being interpreted. To get the main file, the special __main__ module can be used:

import __main__ as main print(main.__file__) 

Note that __main__.__file__ works in Python 2.7 but not in 3.2, so use the import-as syntax as above to make it portable.

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.

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.

Читайте также:  Php сгенерировать уникальный идентификатор

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.

Yoel 8639

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 .)

  • How to get python file name in decorator function in inherited file
  • Why does python script in current directory need ./ for execution with shebang?
  • Get location of bash script that called python script
  • Python script to query google maps and get the resulting URL
  • Generate a text file with the name of current time in Python
  • Get values from SQL table along with column name as list in Python
  • How to get current url of a parsed HTML page in Python with lxml?
  • Python script to read from a file and get values
  • How to get container name from container ID using python docker module
  • How can I get Atom’s script package to run a script from the script’s current working directory?
  • Using MatchFiles() in apache beam pipeline to get file name and parse json in python
  • Unable to get PID of a process by name in python
  • How to get the script path of a python process who’s cmdline is [«python»], with no path?
  • How to get device name for a mount in python
  • Python ctypes — get name of CFUNCTYPE
  • Get label name on JSON Python
  • How can I get an html for to run a python script on submit?
  • Why does this Python code get the name error?
  • Python parsedatetime: get current month / first of the month
  • Get result to python variable after executing R script
Читайте также:  Python set list index

More Query from same tag

  • Python cron job file access
  • How to point to custom stubs directory in mypy via MYPY environment variable or mypy_path variable
  • Visualizing sobel gradient in python
  • Are fast candlestick charts possible in Python
  • insert a node at Nth position in linked list in python
  • Linux run shell cmd from python, Failed to load config file
  • Why can’t PyCharm show PyTorch Module object attributes in debug mode
  • Java equivalent of Python’s slice
  • ‘Maximum Recursion depth exceeded’ whenever I do OOP
  • How is user input converted into a list with Python?
  • Function That Computes Sum of Squares of Numbers in List
  • QGIS terminates on importing opencv in python
  • Import module to virtual environment on airflow
  • How can I add custom signs to spaCy’s punctuation functionality?
  • formatting date, time and string for filename
  • Is there a way to examine how much memory an image is occupying with python?
  • Python 3 — Help formatting array/table output
  • Detect and remove rectangles surrounding character
  • Time-complexity for text analyser code in python
  • Writing Data to an output file in Python
  • IMPORT job disappears when using sqlalchemy-cockroachdb
  • Seaborn histogram makes columns white
  • How to fix an error with function mod in Sagemath?
  • Doesn’t pop() if a number follows a number
  • How to get domain name for any site?
  • Regular expression to match all words ending with and containing three ‘e’s
  • How to patch the now method of datetime while preserving other methods?
  • Can dict been shared between parent process and child process?
  • Setting a default for nosuchelementexception for multiple variables in python
  • Python Project Structure — multiple files and modules
  • Understanding the behavior of Keras EarlyStopping
  • Cannot properly position QGraphicsRectItem in scene
  • ImportError: DLL load failed while importing win32print
  • Python: AttributeError: ‘module’ object has no attribute ‘WD_BREAK’
  • Descriptor protocol implementation of property()

Источник

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