# %cd command_line
# Note:
#Above was the original code given by Microsoft.
# This will work the first time, but if you re-run these cells
# you may encounter errors so we changed it to...
# ************** DO NOT MODIFY OR ADD ANYTHING TO THIS CODE SEGMENT ***********
# ************** Click Edit> Clear All Outputs ***********
# ************** This code segment must be run before attempting any of the tasks or examples in this lesson ********************
# ************** This cell is a reset cell to remove (if they exist) the parent_dir and any children or leaves
# It prepares the directories and files necessary to run the examples and complete the tasks.
# This cell can be run first then all others cells in this notebook can be run, then this cell can be rerun
# This is the reset. It uses the import shutil (or shell utility) which you will learn later in the course
import os, shutil # shutil = shell utility has an important method called rmtree()
# linux does not have an equivalent command!
# Navigate to `library` directory (if not already in it)
current_path = os.getcwd()
print(current_path)
if ("content" in current_path):
#JGif ("library" in current_path):
nb_path = current_path.split("content")[0] # nb_path = the 1st item in the split list
else:
nb_path = current_path
print("Changing working dir to directory above parent_dir")
os.chdir(os.path.join(nb_path,"content"))
current_path = os.getcwd()
print("Current working directory:", current_path)
if (os.path.exists('parent_dir') == True):
shutil.rmtree('parent_dir')
os.mkdir('parent_dir')
os.chdir('parent_dir')
os.mkdir('child1_dir')
os.chdir('../')
current_path = os.getcwd()
print("Current working directory:", current_path)#
#this magic code will be used as a reset the linux directory so the notebook can be rerun
%mkdir command_line
%cd command_line
!pwd
/work
Changing working dir to directory above parent_dir
Execution error
FileNotFoundError: [Errno 2] No such file or directory: '/work/content'
%%writefile main_script.py
# Start of Python code
# Will be called from another script
def func():
print("Running func")
# Execute when running the script directly
def main():
print("Running the main function")
if __name__ == "__main__":
main()
Writing main_script.py
%%bash
python3 main_script.py
Running the main function
%%writefile secondary_script.py
# Start of Python code
import main_script
# call func() from the main script
main_script.func()
Writing secondary_script.py
%%bash
python3 secondary_script.py
Running func
# [ ] The following program asks the user for a circle radius then display the area and circumference
# Modify the program so it only displays the information when executed directly
# Hint: that would include name and main in there somehwere
# The program should not display anything if it is imported as a module
from math import pi
def circle_area(r):
return pi * (r ** 2)
def circle_circumference(r):
return 2 * pi * r
radius = float(input("Enter radius: "))
print("Area =", circle_area(radius))
print("Circumference =", circle_circumference(radius))
Area = 78.53981633974483
Circumference = 31.41592653589793
%cd command_line
%%bash
ls
init.ipynb
main_script.py
ModuleTenLessonThreeActivityColab.ipynb
notebook.ipynb
__pycache__
secondary_script.py
%%bash
ls -l
total 12
-rw-rw-r-- 1 root root 4569 Jan 1 01:53 init.ipynb
-rw-r--r-- 1 root root 239 Dec 30 03:26 main_script.py
-rw-rw-r-- 1 root root 53791 Jan 1 02:10 ModuleTenLessonThreeActivityColab.ipynb
-rw-rw-r-- 1 root root 3149 Dec 30 04:01 notebook.ipynb
drwxr-xr-x 2 root root 3 Dec 30 03:26 __pycache__
-rw-r--r-- 1 root root 98 Dec 30 03:26 secondary_script.py
%%bash
ls -l -a
total 24
drwxrwxrwx 4 root root 9 Jan 1 02:10 .
drwxr-xr-x 1 root root 133 Jan 1 01:53 ..
drwxrwxr-x 2 root root 3 Dec 30 03:25 .deepnote
-rw-rw-r-- 1 root root 4569 Jan 1 01:53 init.ipynb
-rw-r--r-- 1 root root 239 Dec 30 03:26 main_script.py
-rw-rw-r-- 1 root root 54408 Jan 1 02:10 ModuleTenLessonThreeActivityColab.ipynb
-rw-rw-r-- 1 root root 3149 Dec 30 04:01 notebook.ipynb
drwxr-xr-x 2 root root 3 Dec 30 03:26 __pycache__
-rw-r--r-- 1 root root 98 Dec 30 03:26 secondary_script.py
!pwd
/work
%%bash
ls -l ../parent_dir
ls: cannot access '../parent_dir': No such file or directory
Execution error
CalledProcessError: Command 'b'\nls -l ../parent_dir\n'' returned non-zero exit status 2.
%cd command_line
[Errno 2] No such file or directory: 'command_line'
/
%pwd # notice you are still in command_line
%%writefile command_line.py
import sys
# Number of arguments
argc = len(sys.argv)
print(argc, "arguments and options were passed")
# List of arguments and options
print("The arguments and options passed are: ")
for i in range(argc):
print("argv[{:d}] = {}".format(i, sys.argv[i]))
Writing command_line.py
%%bash
python3 command_line.py arg1 arg2 -option1 -option2
5 arguments and options were passed
The arguments and options passed are:
argv[0] = command_line.py
argv[1] = arg1
argv[2] = arg2
argv[3] = -option1
argv[4] = -option2
%pwd # notice you are still in command_line
%%writefile rand.py
import argparse
from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Parse command-line arguments
args = parser.parse_args()
# Program
print(randint(0, 10))
Writing rand.py
%%bash
python3 rand.py
6
%%bash
python3 rand.py -i
usage: rand.py [-h]
rand.py: error: unrecognized arguments: -i
Execution error
CalledProcessError: Command 'b'\npython3 rand.py -i\n'' returned non-zero exit status 2.
%%bash
python3 rand.py -h
usage: rand.py [-h]
optional arguments:
-h, --help show this help message and exit
%%writefile rand.py
import argparse
from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Parse command-line arguments
args = parser.parse_args()
# Program
for i in range(args.count):
print(randint(0, 10))
Overwriting rand.py
%%bash
python3 rand.py
usage: rand.py [-h] count
rand.py: error: the following arguments are required: count
Execution error
CalledProcessError: Command 'b'\npython3 rand.py\n'' returned non-zero exit status 2.
%%bash
python3 rand.py -h
usage: rand.py [-h] count
positional arguments:
count Count of random integers to be generated
optional arguments:
-h, --help show this help message and exit
%%bash
python3 rand.py 4
7
1
9
10
%%writefile rand.py
import argparse
from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = 'number', nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
# Parse command-line arguments
args = parser.parse_args()
# Program
for i in range(args.count):
print(randint(args.range[0], args.range[1]))
Overwriting rand.py
%%bash
python3 rand.py 4
6
2
6
9
%%bash
python3 rand.py 4 -r 500 1000
687
820
938
939
%%bash
python3 rand.py 4 --range 500 1000
546
636
863
787
%%bash
python3 rand.py 10 -r 500 1000
943
639
606
957
697
663
570
564
515
613
%%bash
python3 rand.py
usage: rand.py [-h] [-r number number] count
rand.py: error: the following arguments are required: count
Execution error
CalledProcessError: Command 'b'\npython3 rand.py\n'' returned non-zero exit status 2.
%%bash
python3 rand.py -h
usage: rand.py [-h] [-r lower upper] [-c] [-m] [-v] count
positional arguments:
count Count of random integers to be generated
optional arguments:
-h, --help show this help message and exit
-r lower upper, --range lower upper
Integer range [a, b] from which the random numbers
will be chosen
-c, --const Generate 10 additional random numbers (in addition to
Count)
-m, --multiply Multiply the number of random numbers by the number of
times this flag appears
-v, --verbose Verbose mode
%%writefile rand.py
import argparse
from random import randint
# define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
# parse command line arguments
args = parser.parse_args()
# program
for i in range(args.count):
print(randint(args.range[0], args.range[1]))
Overwriting rand.py
%%bash
python3 rand.py -h
usage: rand.py [-h] [-r lower upper] count
positional arguments:
count Count of random integers to be generated
optional arguments:
-h, --help show this help message and exit
-r lower upper, --range lower upper
Integer range [a, b] from which the random numbers
will be chosen
%%writefile rand.py
import argparse
from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', metavar = 'rands', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
# Parse command-line arguments
args = parser.parse_args()
# Program
for i in range(args.count): # still accessed as args.count (not args.rands)
print(randint(args.range[0], args.range[1]))
Overwriting rand.py
%%bash
python3 rand.py -h
usage: rand.py [-h] [-r lower upper] rands
positional arguments:
rands Count of random integers to be generated
optional arguments:
-h, --help show this help message and exit
-r lower upper, --range lower upper
Integer range [a, b] from which the random numbers
will be chosen
%%writefile rand.py
import argparse
from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Verbose mode')
# Parse command-line arguments
args = parser.parse_args()
# Program
if args.verbose:
print("Generating {:d} random integer in the range [{:d}, {:d}]".format(args.count, args.range[0], args.range[1]))
for i in range(args.count):
print(randint(args.range[0], args.range[1]))
Overwriting rand.py
%%bash
python3 rand.py 4 --range 500 1000 -v
Generating 4 random integer in the range [500, 1000]
597
545
568
920
%%bash
python3 rand.py -h
usage: rand.py [-h] [-r lower upper] [-v] count
positional arguments:
count Count of random integers to be generated
optional arguments:
-h, --help show this help message and exit
-r lower upper, --range lower upper
Integer range [a, b] from which the random numbers
will be chosen
-v, --verbose Verbose mode
%%writefile rand.py
import argparse
from random import randint
# Define an argument parser object
parser = argparse.ArgumentParser()
# Add positional arguments
parser.add_argument('count', action = 'store', type = int, help = 'Count of random integers to be generated')
# Add optional arguments
parser.add_argument('-r', '--range', metavar = ('lower', 'upper'), nargs = 2, type = int, default = [0, 10], help = 'Integer range [a, b] from which the random numbers will be chosen')
parser.add_argument('-c', '--const', action = 'store_const', const = 10, default = 0, help = 'Generate 10 additional random numbers (in addition to Count)')
parser.add_argument('-m', '--multiply', action = 'count', help = 'Multiply the number of random numbers by the number of times this flag appears')
parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Verbose mode')
# Parse command-line arguments
args = parser.parse_args()
# Program
# If args.const is used, add 10 to the count entered by the user
num_of_rands = (args.count + args.const)
# When args.multiply is not used, its value is None
if (args.multiply != None):
num_of_rands = num_of_rands * args.multiply
if args.verbose:
print("Generating {:d} random integer in the range [{:d}, {:d}]".format(num_of_rands, args.range[0], args.range[1]))
for i in range(num_of_rands):
print(randint(args.range[0], args.range[1]))
Overwriting rand.py
%%bash
python3 rand.py 4 --range 500 1000 -v -c
Generating 14 random integer in the range [500, 1000]
586
781
897
710
526
823
681
540
716
795
788
520
598
683
%%bash
python3 rand.py 4 --range 500 1000 -v -mmm
Generating 12 random integer in the range [500, 1000]
768
689
544
922
981
767
657
993
556
908
516
786
%%bash
python3 rand.py -h
usage: rand.py [-h] [-r lower upper] [-c] [-m] [-v] count
positional arguments:
count Count of random integers to be generated
optional arguments:
-h, --help show this help message and exit
-r lower upper, --range lower upper
Integer range [a, b] from which the random numbers
will be chosen
-c, --const Generate 10 additional random numbers (in addition to
Count)
-m, --multiply Multiply the number of random numbers by the number of
times this flag appears
-v, --verbose Verbose mode
%%writefile day_finder.py
# [ ] Write a program that reads a date (month, day, year) as command-line arguments in order
# then prints the day of the week for that date.
# If an optional flag (-c or --complete) is specified, the program should print the full date (not only the day of the week).
# The help message should look like:
'''
usage: day_finder.py [-h] [-c] month day year
positional arguments:
month Month as a number (1, 12)
day Day as a number (1, 31) depending on the month
year Year as a 4 digits number (2018)
optional arguments:
-h, --help show this help message and exit
-c, --complete Show complete formatted date
'''
# IMPORTANT - all previous cells need to have been run (in order) BEFORE writing and running this cell.
# HINT: Use a date object with strftime
# Define an argument parser object
# Add positional arguments
# Add optional arguments
# Parse command-line arguments
import argparse
import sys
from datetime import date
parser = argparse.ArgumentParser(description="Get day of the week from a date")
parser.add_argument("date", nargs="?", help="Date (mm/dd/yyyy)", default=None)
arguments = parser.parse_args()
use_arguments = True if arguments.date is not None else False
while True:
if use_arguments:
date_input = arguments.date
else:
date_input = input("Enter the date (mm/dd/yyyy): ")
date_list = date_input.split("/")
month = int(date_list[0])
day = int(date_list[1])
year = int(date_list[2])
date_date = date(year, month, day)
except:
print("Invalid date")
if use_arguments:
sys.exit()
continue
break
n_day_of_week = date_date.weekday()
days_of_week = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday",)
day_of_week = days_of_week[n_day_of_week]
print(day_of_week)
Overwriting day_finder.py
%%bash
python3 day_finder.py 12 31 2017 -c
File "day_finder.py", line 54
except:
^
SyntaxError: invalid syntax
Execution error
CalledProcessError: Command 'b'\npython3 day_finder.py 12 31 2017 -c\n'' returned non-zero exit status 1.
%%bash
python3 day_finder.py 12 31 2017
File "day_finder.py", line 54
except:
^
SyntaxError: invalid syntax
Execution error
CalledProcessError: Command 'b'\npython3 day_finder.py 12 31 2017\n'' returned non-zero exit status 1.
%%writefile sort_numbers.py
# [ ] Write a program that reads an unspecified number of integers from the command line,
# then prints out the numbers in an ascending order
# The program should have an optional argument to save the sorted numbers as a file named `sorted_numbers.txt`
# The help message should look like:
'''
usage: sort_numbers.py [-h] [-s] [numbers [numbers ...]]
positional arguments:
numbers int to be sorted
optional arguments:
-h, --help show this help message and exit
-s, --save save the sorted numbers on a file (sorted_numbers.txt)
'''
# IMPORTANT - all previous cells need to have been run (in order) BEFORE writing and running this cell.
# --Complete the following--
#HINT: use nargs = '*' in an add_argument method
# Define an argument parser object
# Add positional arguments
# Add optional arguments
# Parse command-line arguments
import sys
n = len(sys.argv)
for i in range(1, n):
print(sys.argv[i], end = " ")
numbers = []
for i in range(1, n):
numbers.append(int(sys.argv[i]))
numbers.sort()
print("numbers in an ascending order:", numbers)
Overwriting sort_numbers.py
%%bash
python3 sort_numbers.py 23 49 5 300 43 582 58 29 62 69 320 60