The Wayback Machine - https://web.archive.org/web/20240717024512/https://www.geeksforgeeks.org/program-to-print-its-own-name-as-output/
Open In App

Program to print its own name as output

Last Updated : 27 Dec, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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.

  • Well the first one argc is the number of arguments passed in to your program.
  • The second one argv is the array which holds the names of all the arguments passed into your program.
  • Along with those arguments there is an extra piece of information stored in the array first cell of that array i.e. argv[0] which is the full path of the file containing the code.

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




# 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:

Python3




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.



Similar Reads

Python | Print the initials of a name with last name in full
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space excep
3 min read
Python IMDbPY – Getting Person name from searched name
In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be name. Syntax : names[0]['name']Here names is the lis
2 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
Program to print the initials of a name with the surname
Given a full name in the form of a string, the task is to print the initials of a name, in short, and the surname in full. Examples: Input: Devashish Kumar GuptaOutput: D. K. GuptaInput: Ishita BhuiyaOutput: I. BhuiyaApproach: The basic approach is to extract words one by one and then print the first letter of the word, followed by a dot(.). For th
9 min read
Python Script to change name of a file to its timestamp
A Digital Timestamp is a sequence of characters(usually a combination of digits and delimiters), identifying the time when a certain event occurred. In computer science, timestamps are generally used for marking the time of the creation of a virtual entity but are not limited to this in its use case. Digital Timestamps are implemented in various st
3 min read
Implement your own word2vec(skip-gram) model in Python
Prerequisite: Introduction to word2vecNatural language processing (NLP) is a subfield of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages. In NLP techniques, we map the words and phrases (from vocabulary or corpus) to vectors of numbers to make the processing easier. These
6 min read
How to create your own Avatar using Python ?
In this article, we will discuss how to create a custom avatar using Python. In order to perform this task. You don't have to create it yourself on software or download it from some website, but a few lines of code will help you to generate an avatar of your choice. We will be using the py-avataaars package from which we will be creating those beau
3 min read
Build Your Own Microservices in Flask
Nowadays Python is everywhere. This is majorly due to its simplicity and wide range of applications. Flask is a lightweight web framework for building web applications in Python. Creating microservices with Flask is straightforward. In this article, we will start with a basic "hello world" microservice. Following that, we'll delve into the creation
5 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
Create your own universal function in NumPy
Universal functions in NumPy are simple mathematical functions. It is just a term that we gave to mathematical functions in the Numpy library. Numpy provides various universal functions that cover a wide variety of operations. However, we can create our universal function in Python. In this article, we will see how to create our own universal funct
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg