Python – common commands

Managing Versions

1. List All Installed Versions

When you run:


pyenv versions

You see:


* system (set by /Users/spiffy/.pyenv/version)
3.7.12
3.13.1
  • system: Refers to the default Python version that comes pre-installed with macOS.
  • 3.7.12 and 3.13.1: These are Python versions you installed using pyenv.

2. Set the Global Version

You can set the default Python version to 3.13.1 globally for your user account:


pyenv global 3.13.1

Verify the change:


pyenv version

Output:


3.13.1 (set by /Users/spiffy/.pyenv/version)

This ensures that python points to 3.13.1 by default in your shell.


3. Set a Local Version

You can also set a specific Python version for a project directory:


pyenv local 3.7.12

This creates a .python-version file in the current directory. When you navigate to this directory, pyenv automatically uses 3.7.12. Outside this directory, the global version (3.13.1) is used.

Verify:


cat .python-version

Output:

3.7.12

4. Use a Specific Version Temporarily

If you want to use 3.7.12 temporarily in your shell session without changing global or local settings:


pyenv shell 3.7.12

Verify:


python --version

Output:

Python 3.7.12

This change only lasts for the current shell session.


5. Verify Active Python

To confirm which Python version is currently active:

And check its path:



which python

It should point to pyenv’s shims, e.g.:


/Users/spiffy/.pyenv/shims/python

6. Removing a Python Version

If you no longer need a specific version (e.g., 3.7.12), you can uninstall it:



pyenv uninstall 3.7.12

Summary of Commands

CommandPurpose
pyenv global <version>Set the global Python version.
pyenv local <version>Set a Python version for the current folder.
pyenv shell <version>Temporarily use a specific version.
pyenv uninstall <version>Remove a specific Python version.

Having multiple versions is helpful, especially if you work on projects requiring different Python versions. Let me know if you’d like further clarification!

Installing Modules into Specific Versions

The error ModuleNotFoundError: No module named 'bs4' occurs because the BeautifulSoup library (bs4) is not installed for the Python version you are using. Here's how to resolve it:


1. Check Your Python Version

Ensure you're using the correct Python version managed by pyenv:



python --version

If it's not the version you set with pyenv, reload your shell or specify the Python version directly:



pyenv global 3.13.1

Verify the Python version again:



python --version

2. Install bs4 for the Active Python Version

Install the BeautifulSoup library using pip:



pip install beautifulsoup4

3. Confirm Installation

Check that the library is installed:



pip show beautifulsoup4

You should see output like this:



Name: beautifulsoup4
Version: 4.x.x
Summary: Screen-scraping library

4. Run the Script Again

Now, retry running your script:



python ~/scripts/clean_html.py /Volumes/TBPirate/-SpiffyProjects-/alma-linux-proxy-setup/Python-commandcommands.html

5. If Using Virtual Environments

If you’re using a virtual environment, activate it first:



pyenv virtualenv 3.13.1 myenv
pyenv activate myenv
pip install beautifulsoup4

6. Verify pip Points to Correct Python

To ensure pip is installing for the correct Python version, check:



which pip

It should point to your pyenv version:



/Users/spiffy/.pyenv/versions/3.13.1/bin/pip

If it doesn’t, try:



python -m pip install beautifulsoup4

Let me know if you encounter further issues!

Basic Commands

  • print(): Outputs data to the console.
  • input(): Gets user input.
  • type(): Returns the type of an object.
  • len(): Returns the length of an object (e.g., list, string).
  • help(): Provides documentation for an object.
  • dir(): Lists attributes and methods of an object.

Math and Numbers

  • abs(x): Returns the absolute value of a number.

  • round(x, n): Rounds a number to n decimal places.

  • pow(x, y): Returns xyx^yxy.

  • sum(iterable): Sums all items in an iterable.

  • min(iterable): Returns the smallest item.

  • max(iterable): Returns the largest item.

  • :

    • math.sqrt(x): Returns the square root of x.
    • math.pi: The value of π\piπ.
    • math.sin(x), math.cos(x): Trigonometric functions.

String Operations

  • "string".lower(): Converts string to lowercase.
  • "string".upper(): Converts string to uppercase.
  • "string".strip(): Removes leading/trailing whitespace.
  • "string".replace("old", "new"): Replaces a substring.
  • "string".split("delimiter"): Splits the string into a list.
  • "delimiter".join(list): Joins list elements into a string.
  • "string".find("substring"): Returns the index of the first occurrence of a substring.

List Operations

  • list.append(item): Adds an item to the end of the list.
  • list.insert(index, item): Inserts an item at a specific index.
  • list.remove(item): Removes the first occurrence of an item.
  • list.pop(index): Removes and returns the item at index.
  • list.sort(): Sorts the list in place.
  • list.reverse(): Reverses the list in place.
  • list.extend(other_list): Appends elements from another list.

Dictionary Operations

  • dict.get(key, default): Returns the value for a key.
  • dict.keys(): Returns a view of dictionary keys.
  • dict.values(): Returns a view of dictionary values.
  • dict.items(): Returns a view of dictionary key-value pairs.
  • dict.update(other_dict): Updates with another dictionary.
  • dict.pop(key): Removes the key and returns its value.

Control Flow

  • if, elif, else: Conditional statements.
  • for item in iterable: Loop over an iterable.
  • while condition: Loop while a condition is true.
  • break: Exits a loop prematurely.
  • continue: Skips the rest of the loop iteration.
  • pass: Does nothing; acts as a placeholder.

File Handling

  • : Opens a file.

    • Modes: r (read), w (write), a (append), rb (read binary).
  • file.read(): Reads the entire file.

  • file.readline(): Reads one line.

  • file.write("text"): Writes text to a file.

  • file.close(): Closes the file.


Error Handling

  • try/except: Handles exceptions.
  • raise Exception("message"): Raises an exception.
  • finally: Code block that always runs.

Classes and Objects

  • class MyClass:: Defines a class.
  • __init__(self): Constructor method.
  • self: Refers to the instance of the class.
  • object.method(): Calls a method of an object.

Modules

  • import module: Imports a module.
  • from module import function: Imports specific functions.
  • import module as alias: Renames a module for convenience.
  • dir(module): Lists the attributes of a module.

Miscellaneous

  • enumerate(iterable): Returns an iterator with index and value pairs.
  • zip(iter1, iter2): Combines iterables into tuples.
  • map(function, iterable): Applies a function to every item.
  • filter(function, iterable): Filters items using a function.
  • lambda args: expression: Creates an anonymous function.

Advanced

  • @decorator: Used to modify the behavior of a function/method.
  • *args, **kwargs: Used for variable-length arguments in functions.
  • with open(filename) as file: Context manager for file handling.
  • assert condition, "message": Assertion for testing conditions.

Let me know if you'd like more details or examples for any specific command!

Scroll to Top