Python 3home |
Introduction to Python
davidbpython.com
To execute scripts from the command line, we must ensure that the OS can find Python.
Please begin by opening a new Terminal or Command Prompt window. At the prompt, type python -V (make sure it is a capital V). (Please note that your prompt may look different than mine.)
Python can be found: python version is displayed
C:\Users\david> python -V Python 3.11.5
Python can be found, but at the wrong version:
david@192 ~ % python -V Python 2.7.16
Python can't be found:
david@192 ~ % python -V 'python' is not a recognized... or 'python': command not found...
If your path is not set correctly to a 3.x version of Python, you can find instructions on setting it in the supplementary documents for this class. You'll need to set the PATH to point to Python to continue with the remaining steps in this lesson. You may also contact your course manager for assistance.
Here we ask Python to run a script directly (without our IDE's help).
If you are in the same directory as the script, you can execute a program by running Python and telling Python the name of the script:
On Windows:
C:\Users\david\Desktop\python_data\02> python 2.1.py
On Mac:
Davids-MBP-3:02 david% python 2.1.py
Please note: if your prompt looks like this: >>>, you have entered the python interactive prompt. Type quit() and hit [Enter] to leave it. If there are any issues finding Python, please contact your course manager for assistance.
Your output goes to the screen, but in truth, it's going to "standard out".
STDOUT can be redirected to other places besides the screen.
hello.py: print a greeting
print('hello, world!')
redirecting STDOUT to a file at the command line (Windows or Mac):
mycomputer% python hello.py # default: to the screen
hello, world!
mycomputer% python hello.py > newfile.txt # redirect to a file (not the screen)
# (we see no output)
mycomputer% cat newfile.txt # Mac: cat spits out a file's contents
hello, world!
C:\> type newfile.txt # Windows: type spits out a file's contents
hello, world!
The 'pipe' character can connect two programs; the output of a will be redirected as the input of b
Mac: direct output to the wc command (count lines, words and characters)
mycomputer% python hello.py | wc
1 2 14 # the output of wc
Windows: direct output to find command (count lines):
mycomputer% python hello.py | find /c /v "" 1
STDIN is the 'input pipe' to our program (usually the keyboard, but can be redirected to read from a file or other program).
import sys
for line in sys.stdin.readlines():
print(line)
filetext = sys.stdin.read() # alternative to above
A program like the above could be called this way, directing a file into our program's STDIN:
mycomputer% python readfile.py < file_to_be_read.txt
We can of course also direct the output of a program into our program's STDIN through use of a pipe:
mycomputer% ls -l | python readfile.py