1

I'm new to programming and I am using Google Colab to go through the exercises from "Learning Python the Hard Way".

I am stuck on exercise 13 as I need to run it using the command line (i.e. $ python3.6 ex13.py first 2nd 3rd).

So I would like to execute a code on a notebook cell using the Colab Terminal if possible.

If this is not possible, please suggest another way if you know any (for example, saving the code to a text file in google drive, and using the Terminal to execute the file). I'm not able to figure this out either.

This is where I'm stuck:

Notebook Cell

And I would like to run this code using the Colab terminal (Here, I tried to save the file as a text file in Google Drive because I was not able to run the code on the Notebook cell using the command line):

Colab Terminal

Python text file saved on Google Drive

Here is the code for your reference:

# p. 72 - Parameters, Unpacking, Variables
from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv

print("This script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

#This is the command to execute the coder using command line: $ python3.6 ex13.py first 2nd 3rd

However, I would like to do this using Google Colab terminal.

1 Answer 1

4

To execute in shell you can use ! :

!python ex13.py aaa bbb ccc

Or %%shell magic:

%%shell
python ex13.py aaa bbb ccc

Though for this to work your ex13.py must by be in your working directory (or at least accessible) and this can be bit counter-intuitive:
your default working directory is not the location on your Google Drive where you have stored your Notebook (and ex13.py) , instead it's /content on Colab's temporary session storage.

So first you either upload your ex13.py to /content ( drag-and-drop from your local filesystem will do) or mount your GDrive to Colab (there's Mount Drive button) and change your working directory to the location of your script with %cd, e.g. %cd "/content/drive/MyDrive/Colab Notebooks"

Colab screenshot

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! That worked. The screenshot in the answer really helped to work out the solution.
Just one more question. Is there a way to execute the command using the terminal? I am getting this error: xercises# !python ex13.py first 2nd 3rd -bash: !python: event not found /content/drive/MyDrive/Colab_Notebooks/Python_Exercises#
@Tanoj , try python ex13.py first 2nd 3rd , in terminal you don't need to add !, that's just for Colab code block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.