无法通过Optparse向Python传递参数

1 投票
2 回答
503 浏览
提问于 2025-04-17 09:08

我写了一个Python程序。每当我用这样的参数运行脚本时:

python script.py -t 它会给我返回当前的时间,格式是unixtime(Unix时间戳)。

但是每当我尝试传递一个参数,比如:

python script.py -c 1325058720 它就会提示LMT没有定义。所以我把代码中的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()

2 个回答

0

你传入的参数根本不重要。在 optparse 试图查看你的参数之前,这行代码就已经执行了:

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

正如你所提到的,LMT 是未定义的,这会导致错误。我不知道你希望在那个时候 LMT 是什么。time.localtime() 是把从纪元开始的秒数转换为本地时间,如果你想要当前时间(如果我理解没错的话),你其实不需要传入任何东西。

所以实际上,你首先说的是:

python script.py -t  # It returns me current time in unixtime.

这是错误的,它并不会这样做。试试看,你会发现它给你一个 NameError: name 'LMT' is not defined 的错误。

1

我之前犯了个错误,就是在函数外面访问了一个变量,这让我没想到。

 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

撰写回答