Skip to content

Latest commit

 

History

History
487 lines (337 loc) · 9.68 KB

File metadata and controls

487 lines (337 loc) · 9.68 KB

Lab 1.1: Python Command Line Basics

Overview

Most people learn Python in IDEs like VS Code or PyCharm, but production environments require command-line proficiency. In this lab, you'll learn to work with Python directly from the Linux terminal.

You'll explore:

  • Python command-line options and flags
  • The interactive REPL (Read-Eval-Print Loop)
  • Built-in help and documentation systems
  • Running Python code without creating files
  • Common Python modules and tools

Prerequisites:

  • SSH access to a Linux VM
  • Basic Linux command-line knowledge

Part 1: SSH into Your VM and Check Python

Step 1: Connect to Your VM

SSH into your Linux VM (use the credentials provided by your instructor):

Step 2: Check Python Availability

# Try the python command
python --version # or python3 if it fails

Expected output:

Python 3.x.x

Step 3: Create a Symlink (if needed)

If python doesn't exist but python3 does, create a symbolic link so you can use python throughout the lab:

# Create symlink (may require sudo)
sudo ln -s $(which python3) /usr/bin/python

# Verify
python --version
python -V

Why this matters: Many scripts and tools expect python to exist. This is a common production environment fix.


Part 2: Explore Python Command-Line Options

Step 1: View Available Options

python --help

Key options you'll see:

Option Description
-c cmd Execute Python code from command line
-m mod Run a library module as a script
-i Enter interactive mode after running script
-V or --version Print Python version
-h or --help Show help message

Step 2: Try Common Flags

Check version:

python -V
python --version

Run a one-liner:

python -c "print('Hello from command line!')"

Calculate something:

python -c "print(2 ** 10)"  # 2 to the power of 10

Run a module:

python -m pydoc list

Note: If you see an error about a module not being installed, that's normal. The system will usually prompt you with installation instructions if needed.


Part 3: Interactive REPL

Step 1: Launch the REPL

python

You should see:

Python 3.x.x (default, ...)
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> is the Python prompt. You can now execute Python code interactively!

Step 2: Hello World

>>> print("Hello, World!")
Hello, World!

Step 3: Variables and Basic Operations

>>> name = "DevOps"
>>> print(f"Hello {name}!")
Hello DevOps!

>>> x = 42
>>> y = 8
>>> x + y
50

>>> x * y
336

Tip: The REPL automatically prints the result of expressions. Notice you don't need print() for the last two commands.

Step 4: Using the Special _ Variable

>>> 100 / 3
33.333333333333336

>>> _ * 3  # _ holds the last result
100.0

>>> round(_, 2)
100.0

The _ variable always holds the result of the last expression in the REPL only. (Note: This doesn't work in scripts, only in interactive mode.)


Part 4: Built-in Help System

Step 1: General Help

>>> help()

You're now in interactive help mode!

help> list
# Shows documentation for list type

Type quit to exit help mode.

Step 2: Help on Specific Objects

>>> help(list)

You'll see:

  • What a list is
  • All available methods
  • How to use each method

Press q to quit the pager.

Step 3: Help on Methods

>>> help(list.append)

Shows:

Help on method_descriptor:

append(self, object, /)
    Append object to the end of the list.

Step 4: Help on an Instance

>>> my_list = [1, 2, 3]
>>> help(my_list)

This shows the same info as help(list), but you can also do:

>>> help(my_list.append)

Step 5: Using dir() to Explore

>>> dir(list)
['__add__', '__class__', ..., 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> my_list = [1, 2, 3]
>>> dir(my_list)
# Same output - shows all available methods

dir() is your friend when you forget what methods an object has!

Step 6: Quick Method Examples

>>> my_list = []
>>> my_list.append(10)
>>> my_list.append(20)
>>> my_list
[10, 20]

>>> my_list.extend([30, 40])
>>> my_list
[10, 20, 30, 40]

>>> my_list.pop()
40
>>> my_list
[10, 20, 30]

Step 7: Exit the REPL

>>> exit()

Or use Ctrl+D (Unix/Linux/Mac) or Ctrl+Z then Enter (Windows).


Part 5: Running Modules with -m

The -m flag runs a Python module as a script. This is commonly used with built-in tools.

Step 1: View Module Documentation

python -m pydoc list

This shows the same documentation as help(list) but from the command line!

Step 2: Browse All Available Modules

# Local access only (default)
python -m pydoc -p 8080

# Access from your browser (open port 8080 in security group first)
python -m pydoc -n 0.0.0.0 -p 8080

This starts a local documentation server. By default it binds to localhost (only accessible on the VM). Use -n 0.0.0.0 to bind to all interfaces, then browse at http://<PUBLIC_IP>:8080 (requires port 8080 open in your security group).

Alternative: Use SSH port forwarding instead of opening the port.

Press Ctrl+C to stop the server.

Step 3: Common -m Usage (One Example)

The -m flag is most commonly used with pip:

python -m pip list

Why use python -m pip instead of just pip?

  • Ensures you're using pip for the correct Python version
  • Works in virtual environments
  • More explicit and safer in automation scripts

Note: If you get an error, the system will usually tell you how to install the missing package.


Part 6: One-Liners with -c

The -c flag lets you run Python code without creating a file. Perfect for quick tasks!

Step 1: Basic Examples

# Print something
python -c "print('Quick test')"

# Math
python -c "print(sum([1, 2, 3, 4, 5]))"

# String manipulation
python -c "print('hello'.upper())"

Step 2: Practical Use Cases

Generate a random password:

python -c "import random, string; print(''.join(random.choices(string.ascii_letters + string.digits, k=16)))"

URL encode a string:

python -c "import urllib.parse; print(urllib.parse.quote('hello world'))"

Real-world usage: These one-liners are great in shell scripts and automation pipelines!


Part 7: Create and Run a Simple Script

Step 1: Create a Python File

# Create a simple script
cat > hello.py << 'EOF'
#!/usr/bin/env python3

name = input("What's your name? ")
print(f"Hello, {name}!")
print(f"Your name has {len(name)} characters.")
EOF

Step 2: Run the Script

python hello.py

Enter your name when prompted.

Step 3: Make it Executable (Optional)

# Make it executable
chmod +x hello.py

# Run it directly
./hello.py

Note the shebang line (#!/usr/bin/env python3) at the top. This tells Linux which interpreter to use.


Part 8: Interactive Mode After Script (-i)

The -i flag runs a script and then drops you into the REPL with all variables still available. Great for debugging!

Step 1: Create a Test Script

cat > variables.py << 'EOF'
x = 42
y = 100
result = x + y
print(f"Result: {result}")
EOF

Step 2: Run with -i Flag

python -i variables.py

Expected output:

Result: 142
>>>

Now you're in the REPL!

>>> x
42
>>> y
100
>>> result
142
>>> result * 2
284
>>> exit()

Why this is useful: When debugging scripts, you can inspect variables and test fixes interactively.


Part 9: Hands-On Challenge

Your task: Create a Python one-liner that:

  1. Imports the datetime module
  2. Gets the current date and time
  3. Formats it as: YYYY-MM-DD HH:MM:SS
  4. Prints it

Hint: Look up datetime.datetime.now() and .strftime() in the REPL:

>>> import datetime
>>> help(datetime.datetime.now)
>>> help(datetime.datetime.strftime)

Solution: (Try it yourself first!)

Click to reveal solution
python -c "import datetime; print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))"

Success Criteria

You've completed this lab when you can:

  • Launch the Python REPL and execute basic commands
  • Use help() and dir() to explore Python objects
  • Create and run a Python script from the command line
  • Execute Python one-liners with -c
  • Use python -m to run modules as scripts
  • Understand when to use python -i for debugging
  • Navigate Python documentation without Google

Key Takeaways

What you learned:

  • REPL skills - Interactive Python is your best learning tool
  • Help system - help(), dir(), and pydoc are always available
  • Command-line Python - Run code without files using -c
  • Module execution - Use -m for built-in tools and scripts
  • Debugging - Use -i to inspect script state interactively

Why this matters:

  • Production servers don't have IDEs
  • Automation scripts need command-line Python
  • Quick testing and debugging happens in the REPL
  • Professional developers use these tools daily

Additional Resources


Congratulations! You're now comfortable with Python from the command line - a critical skill for DevOps and automation work!