Open In App

Program to print its own name as output

Ever thought about writing a script which prints its own name when you execute it. It’s pretty simple. You must have noticed programs in which the main function is written like this

int main(int argc, char** argv)

and you must have wondered what these 2 arguments mean.



To print the name of the program all we need to do is to slice the filename out of that path.

Implementation



Below is the python implementation of the idea discussed above. Let’s suppose the name of the script is print_my_name. 




# Python program to prints it own name upon execution
import sys
 
def main():
    program = sys.argv[0] # argv[0] contains the full path of the file
 
    # rfind() finds the last index of backslash
    # since in a file path the filename comes after the last '\'
    index = program.rfind("\\") + 1
 
    # slicing the filename out of the file path
    program = program[index:]
    print("Program Name: % s" % program)
 
# executes main
if __name__ == "__main__":
    main()

Output: print_my_name.py

Note: The output will vary when you run it on GeeksforGeeks online compiler. 

Use the file global variable:

To get the name of the script in a different way, you can use the __file__ global variable. This variable contains the absolute path to the script file. You can then split the path and take the last element to get the name of the script file.

Here’s an example of how you can use __file__ to get the name of the script:




import os
 
def main():
    script_path = __file__
    script_name = os.path.split(script_path)[1]
    print("Script Name:", script_name)
 
if __name__ == "__main__":
    main()

Output:

Script Name: 0c45e54b-7552-4a18-a0cf-134c8febb77e.py

This will print the name of the script file, just like the previous example. However, this approach does not require the use of the sys module or any string slicing.


Article Tags :