#!/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>'''