1

我写了这个python程序。每当我使用参数运行脚本时

python script.py -t 它以 unixtime 形式返回当前时间。

但是每当我尝试传递一个论点时

python script.py -c 1325058720 它说LMT没有定义。所以我从

LMT = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())

然后它只是跳过我的参数并返回本地时间的当前时间。

有人可以帮我在 LMT 中传递一个参数并将其转换为可读时间格式。我需要向它传递一个参数并以本地时间可读格式查看输出

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()
4

2 回答 2

1

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
于 2011-12-29T06:02:11.050 回答
0

你传入的参数是完全不相关的。在 optparse 甚至尝试查看您的参数之前,执行此行:

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.

于 2011-12-28T10:17:41.530 回答