Skip to content

FAQ

This section lists some frequently asked questions.

How to Get the Current Path

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

python
# -*- coding:utf-8 -*-
# test.py

import os

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

Running the script gives:

bash
$ python3 test.py
/Users/michael/workspace/testing

How to Get the File Name of the Current Module

You can get the file name of the current module using the special variable __file__:

python
# -*- coding:utf-8 -*-
# test.py

print(__file__)

Output:

bash
$ python3 test.py
test.py

How to Get Command Line Arguments

Command line arguments can be accessed using the sys module's argv:

python
# -*- coding:utf-8 -*-
# test.py

import sys

print(sys.argv)

Output:

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

The first element of argv is always the .py file name used to execute the script.

How to Get the Path of the Current Python Command Executable

The executable variable in the sys module provides the path to the Python command's executable:

python
# -*- coding:utf-8 -*-
# test.py

import sys

print(sys.executable)

On macOS, the result may look like:

bash
$ python3 test.py
/usr/local/opt/python3/bin/python3.12
FAQ has loaded