2011-12-28 21 views
1

我已經寫了這個python程序。每當我運行腳本使用參數如無法使用Optparse將參數傳遞給python

python script.py -t它返回我當前時間在unixtime。

,但每當我試圖傳遞一個參數一樣

蟒蛇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() 
+0

我錯了,訪問變量之外的函數沒有點擊我。 – shobhit 2011-12-28 10:52:28

回答

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 
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

+0

我想將任何給定的參數轉換爲本地時間並在控制檯上打印它的輸出。那麼我已經找到了解決辦法。謝謝 – shobhit 2011-12-28 10:48:26