CodeBlanks Logo Icon CodeBlanks

python -c and scripts

Learn to run scripts from the command line.

What is a script file?

You can save Python code to a file and run it from the terminal. This file is called a script and has the .py extension.

For example you write print("Hello") into hello.py and run it with python3 hello.py.

Unlike the REPL, a script file runs all the code from top to bottom. The REPL runs line by line. For large programs you use a script file.

python3 -c for a one-liner

Sometimes you want to run a short piece of code without saving it to a file. For this you use the python3 -c flag:

python3 -c 'print("Hello")'

-c is short for 'command'. It runs the code inside the quotes and exits. It is very handy for a quick calculation or check.

Unlike a script file this is not permanent; the code is not saved.

Practice Complete the script

Complete the script below so that it prints Script ran to the screen with print. Add an explanatory comment at the top.

Starter code

main.py
# This script prints a message to the screen

Sample solution

main.py
# This script prints a message to the screen
print("Script ran")

Expected output

Script ran

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the script extension

Question
# file name: hello____
print("Hello")
Answer
# file name: hello.py
print("Hello")

Explanation: Python scripts are saved with the .py extension.

2 Which command runs merhaba.py?

  • python3 merhaba.py Correct answer
  • execute merhaba.py
  • run merhaba.py
  • merhaba.py run

Explanation: python3 merhaba.py runs the file.

3 Match each way to run Python

Term Meaning
python3 file.py Run a script
python3 -c '...' Run a one-liner
python3 Start the REPL
exit() Leave the REPL

All lessons in Beginner