无法使用Optparse将参数传递给python

时间:2011-12-28 08:04:02

标签: python optparse

我写过这个python程序。每当我使用像

这样的参数运行脚本时

python script.py -t它在unixtime中返回当前时间。

但每当我尝试传递像

这样的论点时

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

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

然后它跳过我的参数并返回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 :(得分: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

答案 1 :(得分:0)

您传入的参数完全无关紧要。在optparse甚至尝试查看你的参数之前的方式,这一行被执行:

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

正如您所指出的,LMT未定义,并会引发错误。 我不知道你对LMT的期望是什么。 time.localtime()将epoch转换为localtime,因为你想要当前时间(如果我理解你),你不需要传入任何东西。

事实上,你首先要说的是:

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

这是错误的,但事实并非如此。尝试一下,你会看到。它会为您提供NameError: name 'LMT' is not defined

相关问题