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:
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):
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.
CodePudding user response:
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