Search code examples
pythonbatch-filesys

Batch file executes Python script with sys.argv[]


I created a custom command scan for the windows terminal which executes a python script.

@echo off
python "my_scripts\scan.py"

For initial tests, I have written this fabulous script.

import sys

print(f"The name of the script is: { sys.argv[0] }")

When I type scan into the shell, as for as I know, this should just print: The name of the script is: scan.

But instead, the output I am getting is: The name of the script is: my_scripts\scan.py.

It´s very obvious what the issue is, but I don´t know how to fix this.


Solution

  • You can use Path.stem to get the name of a file without the extension

    __file__ is the full path to the current file which you can pass to Path

    from pathlib import Path
    
    print(f"The name of the script is: {Path(__file__).stem}")
    

    You can also pass sys.argv[0] instead if you want to

    from pathlib import Path
    import sys
    
    print(f"The name of the script is: {Path(sys.argv[0]).stem}")