How To Get Current Path, Current Module File Name, Command Line Parameter And Executable File Path In Python.

1. How To Get The Current Path.

The current path can be represented by '.', and then converted to an absolute path by os.path.abspath().

import os
print(os.path.abspath('.'))

Running result.

$ python3 get_curr_path.py 
/Users/jerry

2. How To Get The File Name Of Current Module.

It can be obtained by the special variable __file__.

print(__file__)

The output.

$ python3 get_curr_module_file.py
get_curr_module_file.py

3. How To Get Command Line Parameters.

It can be obtained by argv of sys module.

import sys
print(sys.argv)

Output.

$ python3 test_cmd_args.py -a -s "Hello world"
['test_cmd_args.py', '-a', '-s', 'Hello world']

The first element of argv is always the .py file name executed from the command line.

4. How To Get The Executable File Path Of The Current Python Command.

The executable variable of the sys module is the path of the Python command executable file.

import sys
print(sys.executable)

Output.

$ python3 test_python_executable.py 
/usr/bin/python3