08_Python_files
08_Python_files
>>> import os
>>> os.getcwd()
'/home/me'
---------------------------------------------
<ipython-input-1-a7440e1156be> in <module>()
hello.py
def print_hello():
print('Hello!')
main_program.py
import hello
hello.print_hello()
Create your own module
If module is in
/home/me/my_modules/hello.py
def print_hello():
print('Hello!')
/home/me/my_scripts/main_program.py
import sys
sys.path.append('/home/me/my_module/')
import hello
hello.print_hello()
Exercise
● Create python file that will contain function divide_two_numbers
● Import this function to a different Python file, main.py, or Jupyter Notebook
● Call function in the second file main.py or in your Jupyter Notebook, e.g.
divide_two_numbers(3,5)
Run python script from command line
Create my_script.py (e.g. in text editor).
$ cat my_script.py
print("Hello world!")
$ python3 my_script.py
Hello world!
Run python script from command line
● Use sys.argv from sys package
● sys.argv is the list of command-line arguments,
the program name is first argument, i.e. sys.argv[0]
import sys
def sum_num(a,b):
return a+b
print(sum_num(int( sys.argv[1]),int(sys.argv[2])))
$ python my_script.py 3 2
5
Argparse
- Library for parsing arguments from the command-line
- Allows easy help integration
- Use of positional or optional arguments
- See the documentation
Argparse import and start
Argparse positional arguments
Argparse positional arguments with help
Argparse positional arguments with type
Argparse optional arguments
Argparse optional arguments with actions
Argparse optional arguments with short options
Argparse combining arguments
Argparse combining arguments and defaults
Exercise
Write a small Python script count_letters.py using argparse that:
The script prints out a list of letters in alphabetical order with the number of
occurrences:
a2
b5
Script structure
Often the script contains a function called “main” just to be clear what is the
purpose of the script. This is, however, not necessary.
On the other hand, the following block can be used to make sure the script’s code
runs only in case the script is directly called:
if __name__ == ’__main__’:
>>> fruit_data
['apples', 'apricots', 'peaches', 'bananas']
Offtopic: timing functions in Jupyter Notebook
● Use Jupyter notebook magic function %%timeit or %%time
● More information here
Exercise
● Create list of things you would like to take on the empty island
● Write this list to the tab-delimited file, so that each element is on a different line and lines are
numbered
● Example
1 casserole
2 book
3 knife
4 water bottle
5 fishing rod