Files
coding-mentor-agent/kb/python-course-kb-practical-python/wiki/exercises/1-33-reading-from-the-command-line.md
T

1.7 KiB
Raw Blame History

id, source_exercise_id, title, section, source_path, source_repo, source_commit, student_visible_solution, has_private_solution, skip
id source_exercise_id title section source_path source_repo source_commit student_visible_solution has_private_solution skip
practical-python-1.33 1.33 Reading from the command line 1.7 Functions 01_Introduction/07_Functions.md https://github.com/dabeaz-course/practical-python 93dca856b41c61a0a0f85ae334116e4c125629ea false true false

Exercise 1.33: Reading from the command line

Source: Practical Python Programming, 01_Introduction/07_Functions.md.

Exercise 1.33: Reading from the command line

In the pcost.py program, the name of the input file has been hardwired into the code:

# pcost.py

def portfolio_cost(filename):
    ...
    # Your code here
    ...

cost = portfolio_cost('Data/portfolio.csv')
print('Total cost:', cost)

That’s fine for learning and testing, but in a real program you probably wouldn’t do that.

Instead, you might pass the name of the file in as an argument to a script. Try changing the bottom part of the program as follows:

# pcost.py
import sys

def portfolio_cost(filename):
    ...
    # Your code here
    ...

if len(sys.argv) == 2:
    filename = sys.argv[1]
else:
    filename = 'Data/portfolio.csv'

cost = portfolio_cost(filename)
print('Total cost:', cost)

sys.argv is a list that contains passed arguments on the command line (if any).

To run your program, you’ll need to run Python from the terminal.

For example, from bash on Unix:

bash % python3 pcost.py Data/portfolio.csv
Total cost: 44671.15
bash %

Contents | Previous (1.6 Files) | Next (2.0 Working with Data)

关联来源