1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os

# Two functions for converting C->F and F->C
def f_to_c ( f ):
    return ( f - 32 ) * 5 / 9.

def c_to_f ( c ):
    return c * 9 / 5. + 32

# This function does only the printing
def ausgabe ( wert, convert, wert0_einheit, wert1_einheit):
    try:
        wert = float ( wert )
    except:
        print 'This is no numeric value: ', wert
        raise
        # Instead of raise the script could terminate using sys.exit(), too.
    else:
        print '%5.2f%s = %5.2f%s' % ( wert, wert0_einheit, \
            convert(wert), wert1_einheit )

# Checking of command line arguments.
# In this script the user MUST pass two command line arguments.
if len ( sys.argv ) == 3:
    if sys.argv[1] == '-cf':
        # Remember: c_to_f is a function. This makes convert() callable!
        convert = c_to_f
        convert_string = 'Converting Celsius -> Fahrenheit'
        wert0_einheit = '°C'
        wert1_einheit = '°F'
    elif sys.argv[1] == '-fc':
        # Remember: c_to_f is a function. This makes convert() callable!
        convert = f_to_c
        convert_string = 'Converting Fahrenheit -> Celsius'
        wert0_einheit = '°F'
        wert1_einheit = '°C'
    else:
        sys.exit ( 1 )

    if sys.argv[2] == 'prompt':
        # This runs the script in an interactive mode.
        print 'Exit with Ctrl+C'
        print convert_string

        while True:
            wert = raw_input ( 'Please insert value [' + wert0_einheit + ']: ' )
            ausgabe ( wert, convert, wert0_einheit, wert1_einheit)
    elif os.path.isfile ( sys.argv[2] ):
        # After checking whether the file really exists the file is read
        # and everything within is processed.
        fd = open ( sys.argv[2], 'r' )
        lines = fd.readlines()
        fd.close()
        print convert_string
        for line in lines:
            line = line.split()
            for wert in line:
                ausgabe ( wert, convert, wert0_einheit, wert1_einheit)
    else:
        # The last option -- value as shell argument -- is considered to be the default.
        print convert_string
        ausgabe ( sys.argv[2], convert, wert0_einheit, wert1_einheit)

else:
    print '''Wrong syntax

Use this scheme:
-cf prompt|<filename>|<Wert>
-fc prompt|<filename>|<Wert>'''