Interacting with Python Command Line

Running Python Scripts

  1. Open Command Prompt/Terminal:

    • On Windows, open Command Prompt (cmd.exe) or PowerShell.
    • On macOS or Linux, open Terminal.
  2. Navigate to Your Python Script’s Directory:

      cd path/to/your/python/script
      
  3. Run a Python Script:

    • To run a Python script, use the python command followed by the script filename:
      python script.py
      
    • Replace script.py with your actual Python script filename.

Interactive Python Shell (REPL)

  1. Open Command Prompt/Terminal.

  2. Start Python Interpreter:

    • Simply type python (or python3 depending on your system configuration):
      python
      
    • This opens the Python interpreter, showing a prompt (»>) where you can enter Python code.
  3. Execute Python Code:

    • To exit the Python interpreter, type exit() or press Ctrl+D (on Unix-like systems) or Ctrl+Z then Enter (on Windows).

Virtual Environments

Managing Python virtual environments is essential for isolating dependencies and project configurations:

  1. Create a Virtual Environment:
    • Using venv (Python 3 built-in module) or virtualenv (third-party package):
      python -m venv myenv
      
  2. Activate the Virtual Environment:
    • On Windows:
      myenv\Scripts\activate
      
    • On macOS/Linux:
      source myenv/bin/activate
      
  3. Install Packages:
    • While the virtual environment is active, install packages using pip:
      pip install package-name
      
  4. Deactivate the Virtual Environment:
    • Simply type deactivate.

Using Python for Automation and Scripts

Python’s command line interface is powerful for automation tasks and scripting. It’s common to use Python scripts for tasks like file manipulation, data processing, and system administration.

By mastering Python’s command line interface, you gain flexibility in executing Python code, managing dependencies, and automating tasks efficiently across different operating systems.