# %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
%%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()
%%bash
python3 main_script.py
%%writefile secondary_script.py
# Start of Python code
import main_script
# call func() from the main script
main_script.func()
%%bash
python3 secondary_script.py
# [ ] 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))
%cd command_line
%%bash
ls
%%bash
ls -l
%%bash
ls -l -a
!pwd
%%bash
ls -l ../parent_dir
%cd 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]))
%%bash
python3 command_line.py arg1 arg2 -option1 -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))
%%bash
python3 rand.py
%%bash
python3 rand.py -i
%%bash
python3 rand.py -h
%%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))
%%bash
python3 rand.py
%%bash
python3 rand.py -h
%%bash
python3 rand.py 4
%%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]))
%%bash
python3 rand.py 4
%%bash
python3 rand.py 4 -r 500 1000
%%bash
python3 rand.py 4 --range 500 1000
%%bash
python3 rand.py 10 -r 500 1000
%%bash
python3 rand.py
%%bash
python3 rand.py -h
%%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]))
%%bash
python3 rand.py -h
%%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]))
%%bash
python3 rand.py -h
%%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]))
%%bash
python3 rand.py 4 --range 500 1000 -v
%%bash
python3 rand.py -h
%%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]))
%%bash
python3 rand.py 4 --range 500 1000 -v -c
%%bash
python3 rand.py 4 --range 500 1000 -v -mmm
%%bash
python3 rand.py -h
%%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)
%%bash
python3 day_finder.py 12 31 2017 -c
%%bash
python3 day_finder.py 12 31 2017
%%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)
%%bash
python3 sort_numbers.py 23 49 5 300 43 582 58 29 62 69 320 60