Skip to content

Commit cff191f

Browse files
committed
Add example of how to use environment variables in Python scripts
1 parent acab0c5 commit cff191f

File tree

5 files changed

+54
-0
lines changed

5 files changed

+54
-0
lines changed

source-code/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ to create it. There is some material not covered in the presentation as well.
2828
configuration files.
2929
1. `data-formats`: illustrates how to deal with data formats such as CSV
3030
files, binary data and XML.
31+
1. `enviroment-variables`: illustrates how to use environment variables to set paths
32+
in a script.
3133
1. `hydra`: Facebook Hydra application framework illustration.
3234
1. `jinja`: illustration of how to use the jinja2 template library.
3335
1. `logging`: illustration of Python's logging facilities.
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Environment variables
2+
3+
This directory shows some examples of how to use environment variables in a Python
4+
script.
5+
6+
## What is it?
7+
8+
1. `accumulate_data.py`: script that will read all `.txt` files in a directory defined
9+
in an environment variable `DATA_DIR`.
10+
1. `data`: directory that contains two text files with data.
11+
12+
## How to use it?
13+
14+
```bash
15+
$ export DATA_DIR="$(pwd)/data"
16+
$ ./accumulate_data.py
17+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python
2+
3+
from glob import glob
4+
import os
5+
from pathlib import Path
6+
import sys
7+
8+
9+
if __name__ == '__main__':
10+
if 'DATA_DIR' in os.environ:
11+
data_dir = Path(os.environ['DATA_DIR'])
12+
print(f"### info: looking for data in '{data_dir}'", file=sys.stderr)
13+
total = 0.0
14+
for data_file in data_dir.glob('*.txt'):
15+
with open(data_file, 'r') as file:
16+
for line in file:
17+
line = line.strip()
18+
if not line:
19+
continue
20+
try:
21+
total += float(line)
22+
except ValueError as error:
23+
print(f'### warning: {error}', file=sys.stderr)
24+
print(f'total = {total}')
25+
else:
26+
print('### error: DATA_DIR not set', file=sys.stderr)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
1.2
2+
2.3
3+
3.4
4+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
4.5
2+
5.6
3+
# dubious values
4+
6.7
5+
7.8

0 commit comments

Comments
 (0)