The Command Line

There are two views of the computer — in the user's view, one just picks up the computer to see text and image and icons. The user clicks and types, the computer reacts to follow their wishes. That's a fantastic story, describing how billions of regular people to use computers to create dazzling results ever day.

But how does that work behind the scenes? The programmers's world putting this all together is driven by the command line.

Command Line

Here's a simple example of the command line, in this case running the command known as "date" which prints the current date and time (works on the Mac and Windows).

$ date
Tue Oct  1 13:49:55 PDT 2019
$

With the command line, the computer types out a prompt, shown here as "$" although typically it is longer, showing things like the current folder. The cursor is left blinking to the right of the prompt, waiting for the user to type something. The user types a command and hits the return (aka enter) key to run the command. In this example, shown in bold, the "date" command. The computer takes in what the user has typed, runs it, prints the resulting output to the screen, and then puts up a prompt again.

The command line is often called the "terminal" since that was the name for the screen and keyboard devices that were wired up to computers in the early days.

Below, we'll show how to get a terminal from within PyCharm which will be our common way to do it. See the "Creating Command Line" at the end of this doc for how to get a command line without PyCharm.

Example Project Folder: hello

For the examples bellow you can use our "hello" project. Download the hello.zip zip file. Move the .zip file the folder where you'd like to keep your code. Expand it to get a "hello" folder that contains a "hello.py" file and some other files. The examples below will use this hello folder as an example for various command.

Windows hello.zip issue: by default Windows expands hello.zip to create a "hello" folder with a second "hello" folder inside it, which is one too many folders. Windows will put up a dialog to choose where the files should go; in that dialog, delete the "hello" off the end to avoid this nesting.

Terminal in a Folder

A command line always runs in the context of a folder on the computer so the commands can have easy access to the files in that folder. What regular users call a "folder" on the computer, programmers user the older term "directory", but it's the same thing — a directory has a name and holds a collection files and sub-directories.

How do you get a command prompt in a directory? There is a very easy way from within PyCharm:

Run PyCharm. Select the Open... menu command. Navigate to the "hello" folder unzipped above. Click on the hello folder and open it (do not click on the "hello.py" file in the folder, maddeningly that does not open the folder in the same way. A common mistake.)

With the hello project opened, click the "Terminal" tab at the lower left, and PyCharm will create a command line terminal in the "hello" directory. This works on the Mac and Windows.

Within the terminal, type the "ls" command, which lists the names of the files and directories in the current folder. (On older Windows, the equivalent command is "dir".) In this way, you can confirm that the command line is running in the correct directory. It should look like the following (the "$" represents the prompt printed before where you type).

$ ls
hello.py        poem.txt        spring.txt      sub

Running Your Python Program

When you write a Python program, you are writing a new command the computer can run. Here we'll use the simple hello.py program which you can practice running to see some output.

In the command line, the command to run the Python hello.py program, the command is:

$ python3 hello.py 
Hello World
$

The first word "python3" means we want to run the Python interpreter which handles python programs, and then "hello.py" refers to the Python program we want to run. Those two words run the Python program in the "hello.py" file, printing any output to the terminal. On Windows instead of "python3" the command is "python" or "py" and everything else is the same.

In this case, the program just prints "Hello World" on one line. When the program is done we get another prompt.

Command Line Arguments

The command line is a powerful and flexible way to specify extra information for a program to use. We can type in extra words after the hello.py name of the program, and these are called "command line arguments". If the hello.py program is run with one command line argument, it treats it as a name to put in the greeting. See how the command line argument comes just after the hello.py file name:

$ python3 hello.py Alice
Hello Alice
$ python3 hello.py Bob
Hello Bob

For the above examples we would say that hello.py took 1 command line argument: "Alice" for the first run and "Bob" for the second.

The Up Arrow

Typing the whole command line again and again is too much work! It has been said that laziness is guiding principle in CS — arrange the machinery to avoid as much work as possible. In the terminal, hit the up arrow key — this should bring back your previous command line. You can arrow left and right to edit this line then hit return to run with it. This is an incredibly useful feature, allowing you to retrieve the command you just did and make little edits to try something else.

Exercise: Use the up-arrow to try different names. (Command line keyboard protips for Mac/linux: ctrl-u deletes the line, ctrl-a and ctrl-e go the start and end of the line.)

-n Options

Typically when a command line argument begins with a dash, like "-n", it enables some option for the command.

For example, see below what hello.py does when run with 3 command line arguments like this:
hello.py -n a-number a-name

$ python3 hello.py -n 100 Alice
Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice Alice 

Normally words on the command line are separated from each other by spaces. Place text inside quote marks to group it together, treating it as a single arg, like this:

$ python3 hello.py -n 10 "Philip K. Dick"
Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick 

Exercise: Use the up-arrow to try different names and values of -n.

Aside: can the hello.py program crash your computer? See the end of this page for this non sequitur question.

Remember the Up Arrow

We are just scratching the surface of how you could run a program and play around with different arguments to run it different ways. Always use the up-arrow to bring back a previous command line for editing; only type out the command from scratch once!

See Files and Directories: ls pwd cat wc

What files are in this directory? What's in this file? We've needed commands to answer those questions from the earliest days of computers. The names chosen within the Unix operating system for these commands have gradually taken over, so now the Mac, Linux, and the new Windows Power Shell command line all support these commands using the same names. (Windows note: Windows also has an older "Command Shell" which uses different names - we'll mention these in parenthesis as we go. By default, PyCharm brings up the old type of shell on Windows.)

The ls command ("list") lists out the files and sub-directories in the current directory (the old windows command for this is "dir"). Here is an example running in the "hello" example directory which ships with a couple .txt files we see in the listing:

$ ls
hello.py        poem.txt        spring.txt      sub
$

The cat command prints out the contents of a file to the screen:

$ cat poem.txt 
Roses are red
Violets are blue
This does not rhyme
$
$ cat spring.txt 
Spring has sprung
Fall has fell
Winter's here
And it's colder than
usual
$

(The old Windows command for this is "type".)

The pwd command ("print working directory") prints out the name of the current directory plus its parent directories. Essentially is shows where the current directory is in the file system. (See "cd" below for the command that changes the current directory.)

$ pwd
/Users/nick/cs106a/code/hello
$

The wc command ("word count") counts and prints out the number of lines, words, and characters that make up a file:

$ wc poem.txt 
       3      10      51 poem.txt
$ wc hello.py 
      43     149     991 hello.py

Windows does not have the "wc" command by that name. The equivalent is this command in Power Shell is:

$ cat poem.txt | Measure-Object -line -word -char

A fair criticism of the Unix commands is that they are short and cryptic. However, with the above I appreciate that short and cryptic is also easy to type.

Calendar - cal

This is Mac Linux only - a simple command that I find myself using all the time. The "cal" command prints out a little calendar of the current month. If you mention a year, it prints that whole year.

$ cal
    January 2022      
Su Mo Tu We Th Fr Sa  
                   1  
 2  3  4  5  6  7  8  
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30 31                 
$ cal 2022
                            2022
      January               February               March          
Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  
                   1         1  2  3  4  5         1  2  3  4  5  
 2  3  4  5  6  7  8   6  7  8  9 10 11 12   6  7  8  9 10 11 12  
 9 10 11 12 13 14 15  13 14 15 16 17 18 19  13 14 15 16 17 18 19  
16 17 18 19 20 21 22  20 21 22 23 24 25 26  20 21 22 23 24 25 26  
23 24 25 26 27 28 29  27 28                 27 28 29 30 31        
30 31                                                             

       April                  May                   June          
Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  
                1  2   1  2  3  4  5  6  7            1  2  3  4  
 3  4  5  6  7  8  9   8  9 10 11 12 13 14   5  6  7  8  9 10 11  
10 11 12 13 14 15 16  15 16 17 18 19 20 21  12 13 14 15 16 17 18  
17 18 19 20 21 22 23  22 23 24 25 26 27 28  19 20 21 22 23 24 25  
24 25 26 27 28 29 30  29 30 31              26 27 28 29 30     
   
... and so on ...

$

Change Directory cd

The command line runs "in" a current directory, with easy access to those files. Normally we create a terminal in the directory containing the Python and data files and never change it.

If needed, the cd command ("change directory"), changes the directory of a command line. The command cd dir-name change the current directory to the one named. The special directory name ".." (two dots), means the parent directory. With "pwd" we can check on where we are.

Protip: typing directory names is a chore and error-prone. Type the first few chars of a name, then hit the Tab key — the command line will attempt to auto-complete the rest of the name for you. This saves work, and is more accurate, since the auto-complete always types the name out correctly.

Suppose the command line is in the "hello" folder, which contains a sub-directory named "sub". Then the following command move the command line down into the sub directory:

# pwd     # verify we're in the "hello" dir
/Users/nick/cs106a/code/hello
$ ls      # in hello directory, list files
hello.py        poem.txt        spring.txt        sub
$ cd sub  # move down into sub directory
$ pwd     # pwd down here in sub
/Users/nick/cs106a/code/hello/sub
$ ls      # list files in sub
a.txt    b.txt    c.txt
$ cd ..   # go back up to hello directory

Using "cd", you can move the command line around to anywhere in your file system. Remember to use tab-completion when typing each directory name.

Capture Output With >

You run the program with different arguments, seeing different outputs. Eventually you want to capture the text output into a file. There's a very easy way to do this: add > out.txt at the right side of the command line. This runs the command again, but instead of printing the output on the screen, the output is captured into the file.

$ python3 hello.py -n 10 "Philip K. Dick" > philips.txt
$ ls    # now philips.txt file exists
hello.py        philips.txt     poem.txt        spring.txt
$ cat philips.txt 
Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick Philip K. Dick 

Creating Command Line Without PyCharm

Creating a command line terminal within PyCharm is one easy way. However you can also do it without PyCharm:

On the Mac: open the Applications > Utilities > Terminal. This creates a command line starting in the home directory. Suppose you have a folder named "courses" and within that a folder named "cs106a". You could use the commands cd courses and then cd cs106a to move the terminal to inside your cs106a folder.

On Windows: Open a file-explorer window on the folder you want the command line in. Do a shift-right-click in an area not on top of a file. Select the "Open PowerShell window here" menu option to create a terminal starting in that folder.

In either case you can use the commands "cd" and "ls" and "pwd" to examine what files are there and change directories.

Timing the Run of a Command

It's handy to measure how many seconds it takes to run a command. On most systems the time command does this (wordcount.py is a CS106A example from the later weeks):

$ time python3 wordcount.py alice-book.txt
...
 -output here we're ignoring-
...

real	0m0.135s
user	0m0.112s
sys	0m0.015s

Here "real 0.135s" printed after the regular output means regular clock time, 0.135 of a second, aka 135 milliseconds, passed during the run of this command.

The Windows PowerShell equivalent to time the run of a command:

$ Measure-Command { python wordcount.py alice-book.txt }

Stopping a Program - ctrl-c

How do you stop a program while it is running? Maybe your program has a bug, producing lots of output, and you just want it to stop. From the early days of the command line typing ctrl-c in a program's terminal stops the program in mid-run ("c" for "cancel").

If you run hello.py normally, it finishes so quickly you won't have a chance to stop it. So you need to give a really large value for the -n argument, like 10 million, to try out the ctrl-c.

$ python3 hello.py -n 10000000 Bob
Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob
 .. a lot of Bobs ..
Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob Bob BobTraceback (most recent call last):
  File "hello.py", line 42, in 
    main()
  File "hello.py", line 36, in main
    print(name, end=' ')
KeyboardInterrupt
$

The program runs along, producing countless Bobs, but then typing ctrl-c interrupts and terminates it mid-run and we get a new command line prompt. The KeyboardInterrupt you see at the end there is the Python terminology for a program interrupted in this way.

Non Sequitur: hello.py Crash?

Here is question about the hello.py program I've always wondered about, but which I've never been brave enough to figure out, so I'll leave it as a question. As hello.py runs and prints out to the terminal, your computer is presumably saving all that text somewhere. Each character takes up one byte. Question: what happens if you run a hello.py command with the number 9 trillion:

$ python3 hello.py -n 9000000000 "Winter Is Coming"
# what happens here? I don't know

Might this causes the computer to lock up at some point, as it runs out of memory or disk space to store all that text? Or perhaps the terminal program starts discarding the text to save itself at some point. Or maybe the process is so slow, ones loses interest before it gets far enough for something interesting to happen. On the Mac, use Activity Monitor and on Windows use the Task Manager to look at what's happening on the computer.

 

Copyright 2020 Nick Parlante