Reputation: 700
i have written this python program. whenever i run the script using parameters like
python script.py -t It returns me current time in unixtime.
but whenever i try to pass an argument like
python script.py -c 1325058720 It says LMT is not defined. So i removed the LMT from the
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())
Then it just skip my argument and returns the current time in Localtime.
Can someone please help me to pass an argument in the LMT and convert it to Readable time format. I need to pass an argument to it and see the output in the localtime readable format
import optparse
import re
import time
GMT = int(time.time())
AMT = 123456789
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(LMT))
VERBOSE=False
def report(output,cmdtype="UNIX COMMAND:"):
#Notice the global statement allows input from outside of function
if VERBOSE:
print "%s: %s" % (cmdtype, output)
else:
print output
#Function to control option parsing in Python
def controller():
global VERBOSE
p = optparse.OptionParser()
p.add_option('--time', '-t', action="store_true", help='gets current time in epoch')
p.add_option('--nums', '-n', action="store_true", help='gets the some random number')
p.add_option('--conv', '-c', action="store_true", help='convert epoch to readable')
p.add_option('--verbose', '-v',
action = 'store_true',
help='prints verbosely',
default=False)
#Option Handling passes correct parameter to runBash
options, arguments = p.parse_args()
if options.verbose:
VERBOSE=True
if options.time:
value = GMT
report(value, "GMT")
elif options.nums:
value = AMT
report(value, "AMT")
elif options.conv:
value = LMT
report(value, "LMT")
else:
p.print_help()
Upvotes: 1
Views: 509
Reputation: 700
I was wrong to access the variable outside the function which didn't clicked me.
elif options.conv:
LMT = options.conv
LMT= float(LMT)
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(LMT))
print '%s'% LMT
Upvotes: 1
Reputation: 172269
The parameters you pass in are completely irrelevant. Way before optparse even tries to look at your parameters, this line is executed:
LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(LMT))
And as you point out, LMT is undefined, and will raise an error. I have no idea what you expect LMT to be at that point. time.localtime() converts a number of seconds from epoch to localtime, since you want the current time (if I understand you) you don't need to pass in anything.
So in fact, you first say that:
python script.py -t # It returns me current time in unixtime.
This is wrong, it does not. Try it and you'll see. It gives you a NameError: name 'LMT' is not defined
.
Upvotes: 0