杰瑞科技汇

如何使用Python列出config配置项?

Of course! The phrase "python config list" can mean a few different things depending on what you're trying to achieve. I'll break it down into the most common interpretations, from the most direct command-line answer to the more general concept of listing configuration in Python code.

如何使用Python列出config配置项?-图1
(图片来源网络,侵删)

The Direct Command-Line Answer: py --list

If you are on Windows and have installed Python from the official python.org installer, you can use the py command to manage multiple Python versions.

To list all the Python versions you have installed, you use the --list or -l flag.

py --list

Example Output:

Installed Pythons found by py Launcher for Windows
 -3.11-64        C:\Users\YourUser\AppData\Local\Programs\Python\Python311\python.exe
 -3.10-64        C:\Users\YourUser\AppData\Local\Programs\Python\Python310\python.exe
 -3.9-64         C:\Users\YourUser\AppData\Local\Programs\Python\Python39\python.exe
 -3.8-32         C:\Users\YourUser\AppData\Local\Programs\Python\Python38-32\python.exe
 -3.11           C:\Python311\python.exe  * This one is the default for the -3.11 tag
  • The -3.11-64 and -3.11 are "tags" you can use to run a specific version.
  • The asterisk indicates the default executable for that tag.

For macOS and Linux

On macOS and Linux, you typically use the which command to find the path of the Python executable you are currently using.

如何使用Python列出config配置项?-图2
(图片来源网络,侵删)
# Find the path of the default python3
which python3
# Example output:
# /usr/bin/python3
# Find the path of the default python2 (if installed)
which python
# Example output:
# /usr/bin/python

To see all installed Python versions, you might need to check your system's package manager or look in common installation directories like /usr/bin/, /usr/local/bin/, or ~/.pyenv/versions/ (if you use pyenv).


Listing Installed Python Packages (pip list)

This is often what people are looking for when they say "config list". They want to see what libraries are installed in their current Python environment.

You can use pip to list installed packages.

# List all installed packages
pip list
# For a cleaner, more organized view, use the --format=freeze option
# This is also the format used for requirements.txt files
pip list --format=freeze

Example Output:

Package         Version
--------------- -------
certifi         2025.7.22
charset-normalizer 3.3.0
idna            3.4
pip             23.2.1
requests        2.31.0
setuptools      68.2.2
urllib3         2.0.7

Listing Outdated Packages

To see which packages have newer versions available, use:

pip list --outdated

Listing Python Configuration Options (The -m way)

Python itself has internal configuration settings. You can view these by running the sysconfig module from the command line. This is useful for seeing where Python is installed, where its libraries go, etc.

python -m sysconfig

Example Output (a snippet):

Platform: "win32"
Python version: "3.11"
Current installation scheme: "nt"
Paths:
        data = "C:\\Users\\YourUser\\AppData\\Local\\Programs\\Python\\Python311\\data"
        include = "C:\\Users\\YourUser\\AppData\\Local\\Programs\\Python\\Python311\\Include"
        platinclude = "C:\\Users\\YourUser\\AppData\\Local\\Programs\\Python\\Python311\\Include"
        platlib = "C:\\Users\\YourUser\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages"
        purelib = "C:\\Users\\YourUser\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages"
        scripts = "C:\\Users\\YourUser\\AppData\\Local\\Programs\\Python\\Python311\\Scripts"
...

Listing Your Own Application Configurations (In Code)

If you mean "how do I list configurations in my Python application", the answer is to use a configuration management library. Here are two popular approaches.

Example A: Using a .env file with python-dotenv

This is a very common pattern for managing environment-specific settings.

  1. Install the library:

    pip install python-dotenv
  2. Create a .env file:

    # .env file
    DATABASE_URL=postgresql://user:password@host:port/database
    API_KEY=your_secret_api_key_12345
    DEBUG_MODE=True
    MAX_RETRIES=3
  3. List (or load) the config in your Python code: You don't typically "list" them in a CLI sense, but you load them into a dictionary or object.

    import os
    from dotenv import load_dotenv
    # Load variables from .env file
    load_dotenv()
    # Now you can access them as environment variables
    config = {
        "database_url": os.getenv("DATABASE_URL"),
        "api_key": os.getenv("API_KEY"),
        "debug_mode": os.getenv("DEBUG_MODE", False), # Provide a default value
        "max_retries": int(os.getenv("MAX_RETRIES", 5)) # Provide a default and cast type
    }
    # To "list" them, you can just print the dictionary
    print("Application Configuration:")
    for key, value in config.items():
        print(f"- {key}: {value}")
    # Or print the whole dictionary
    # print(config)

Output:

Application Configuration:
- database_url: postgresql://user:password@host:port/database
- api_key: your_secret_api_key_12345
- debug_mode: True
- max_retries: 3

Example B: Using a config.py file

This is a simpler, more direct approach.

  1. Create a config.py file:

    # config.py
    DATABASE_URL = "postgresql://user:password@host:port/database"
    API_KEY = "your_secret_api_key_12345"
    DEBUG_MODE = True
    MAX_RETRIES = 3
  2. Import and list the config in your main application:

    # main_app.py
    from config import DATABASE_URL, API_KEY, DEBUG_MODE, MAX_RETRIES
    # To "list" them, you can print the variables directly
    print("Application Configuration:")
    print(f"- DATABASE_URL: {DATABASE_URL}")
    print(f"- API_KEY: {API_KEY}")
    print(f"- DEBUG_MODE: {DEBUG_MODE}")
    print(f"- MAX_RETRIES: {MAX_RETRIES}")
    # Or, for a more dynamic approach, you can use the vars() function
    # print("\nListing all variables from config.py:")
    # for key, value in vars().items():
    #     if not key.startswith('_'):
    #         print(f"- {key}: {value}")

Summary

What you want to do The Command / Method
List installed Python versions (on Windows) py --list
List installed Python packages pip list
View Python's internal configuration paths python -m sysconfig
List my app's settings from a .env file (in code) Use python-dotenv, then os.getenv() to load them into a dict and print it.
List my app's settings from a config.py file (in code) Import the variables and print them, or use vars() to inspect the module.
分享:
扫描分享到社交APP
上一篇
下一篇