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
SSH into your Linux VM (use the credentials provided by your instructor):
# Try the python command
python --version # or python3 if it failsExpected output:
Python 3.x.x
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 -VWhy this matters: Many scripts and tools expect python to exist. This is a common production environment fix.
python --helpKey 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 |
Check version:
python -V
python --versionRun a one-liner:
python -c "print('Hello from command line!')"Calculate something:
python -c "print(2 ** 10)" # 2 to the power of 10Run a module:
python -m pydoc listNote: 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.
pythonYou 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!
>>> print("Hello, World!")
Hello, World!>>> name = "DevOps"
>>> print(f"Hello {name}!")
Hello DevOps!
>>> x = 42
>>> y = 8
>>> x + y
50
>>> x * y
336Tip: The REPL automatically prints the result of expressions. Notice you don't need print() for the last two commands.
>>> 100 / 3
33.333333333333336
>>> _ * 3 # _ holds the last result
100.0
>>> round(_, 2)
100.0The _ variable always holds the result of the last expression in the REPL only. (Note: This doesn't work in scripts, only in interactive mode.)
>>> help()You're now in interactive help mode!
help> list
# Shows documentation for list type
Type quit to exit help mode.
>>> help(list)You'll see:
- What a list is
- All available methods
- How to use each method
Press q to quit the pager.
>>> help(list.append)Shows:
Help on method_descriptor:
append(self, object, /)
Append object to the end of the list.
>>> 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)>>> 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 methodsdir() is your friend when you forget what methods an object has!
>>> 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]>>> exit()Or use Ctrl+D (Unix/Linux/Mac) or Ctrl+Z then Enter (Windows).
The -m flag runs a Python module as a script. This is commonly used with built-in tools.
python -m pydoc listThis shows the same documentation as help(list) but from the command line!
# 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 8080This 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.
The -m flag is most commonly used with pip:
python -m pip listWhy 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.
The -c flag lets you run Python code without creating a file. Perfect for quick tasks!
# Print something
python -c "print('Quick test')"
# Math
python -c "print(sum([1, 2, 3, 4, 5]))"
# String manipulation
python -c "print('hello'.upper())"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!
# 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.")
EOFpython hello.pyEnter your name when prompted.
# Make it executable
chmod +x hello.py
# Run it directly
./hello.pyNote the shebang line (#!/usr/bin/env python3) at the top. This tells Linux which interpreter to use.
The -i flag runs a script and then drops you into the REPL with all variables still available. Great for debugging!
cat > variables.py << 'EOF'
x = 42
y = 100
result = x + y
print(f"Result: {result}")
EOFpython -i variables.pyExpected 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.
Your task: Create a Python one-liner that:
- Imports the
datetimemodule - Gets the current date and time
- Formats it as:
YYYY-MM-DD HH:MM:SS - 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'))"You've completed this lab when you can:
- Launch the Python REPL and execute basic commands
- Use
help()anddir()to explore Python objects - Create and run a Python script from the command line
- Execute Python one-liners with
-c - Use
python -mto run modules as scripts - Understand when to use
python -ifor debugging - Navigate Python documentation without Google
What you learned:
- REPL skills - Interactive Python is your best learning tool
- Help system -
help(),dir(), andpydocare always available - Command-line Python - Run code without files using
-c - Module execution - Use
-mfor built-in tools and scripts - Debugging - Use
-ito 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
Congratulations! You're now comfortable with Python from the command line - a critical skill for DevOps and automation work!