Data Analysis and Visualization with Python | Set 2

Learn examples from DataCamp guru:

Ever thought about writing a script that prints its name on startup. It`s pretty straightforward. You have probably noticed programs where the main function is written like this

 int main (int argc, char ** argv) 

and you must have wondered what these 2 arguments.

  • First argc — this is the number of arguments passed to your program.
  • The second argv argument — it is an array containing the names of all the arguments passed to your program.
  • Along with these arguments, there is an additional piece of information stored in the first cell of the array of this array, i.e. argv [0], which is the full path to the file containing the code.

To print the name of the program, all we have to do is strip the filename from this path.


Below is the implementation of the idea discussed above in python. Let`s assume the script name — print_my_name.

# Python program to print its name at runtime

import sys


def main ():

program = sys.argv [ 0 ] # argv [0] contains the full path to the file


# rfind () finds the last backslash index

# because the filename in the file path follows the last & # 39; / & # 39;

index = program.rfind ( "" ) + 1


# strip the filename from the file path

  program = program [index:]

print ( " Program Name:% s " % program)

# executes main

if __ name__ < code class = "keyword"> = = "__ main__" :

main ()


Note . The output will be different if you run it on the Python.Engineering online compiler.

This article courtesy of Palash Nigam . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic discussed above.

Learn examples from DataCamp guru: