[Python]: Using Python Through Command Line

Level of Difficulty: Beginner.

Sandra has asked you if you can give her a crash course on how to use Python through the command line. So you decide to show her how to run a few Python commands and maybe install a library. Here’s what you can do.

What are the steps?

The steps that we will be following are:

  1. Finding the appropriate Python interpreter command
  2. Running test commands
    1. Create a new Python script
    2. Run the Python script
  3. Install a library

Deep Dive

Let’s dive deeper into the steps listed above.

Finding The Appropriate Python Interpreter Command

Open up command line prompt by hitting the Windows key + r. This will open the run pop up.

In here, type cmd and hit enter. This will open your command line prompt.

Try one of the following commands until you find one that successfully opens Python in the command line for you:

  • python
  • python3
  • py
  • python.exe (if you’re executing from a virtual environment)

In my case, py is the command that instantiates Python in command line, as seen above. Now run the exit() command to exit Python so that we can create the Python script

Running Test Commands

Let’s create a basic print(“Hello Universe”) Python script named TestScript.py by using the following command:

echo print('Hello Universe') > TestScript.py

You should be able to see the newly created file if you run the following command:

dir *.py

Let’s check what happens if we try executing this Python script using by running: (please note that if py did not work for you, use the one that works instead)

py TestScript.py

You should see the following:

Let’s say Sandra asks how to edit the Python code an IDE, run the following command:

TestScript.py

This should pop the code open in the default Python IDE: (mine is PyCharm)

Installing a Library

Now let’s test pip installing a library using the following command: (using the numpy library as an example)

py -m pip install numpy

You’d ideally like to see an indicator that the install was successful. Are you seeing the following?

If you are seeing the same as me, try the command below:

py -m pip install numpy --user

You should now be seeing the following:

After this, Sandra should know enough to get her through the basics of using Python through Command Line

Got stuck somewhere? Want to give some feedback? Please leave a comment below or reach out to jacqui.jm77@gmail.com

2 thoughts on “[Python]: Using Python Through Command Line

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: