Python输出到命令行;错误未定义

时间:2013-05-29 14:51:56

标签: python function command-line output

我正在尝试编写一个脚本,它接受一个参数并将输出写入命令窗口。出于某种原因,我收到错误:

NameError: name 'month' not defined

以下是整个脚本:

import sys


hex = str(sys.argv)
sys.stdout.write (month(hex) + " " + day(hex) + ", " + year(hex) + " " + hour(hex) + ":" + minute(hex) + ":" + second(hex))

def year (hex):
    year = int(hex[0:2], 16)
    year = year + 1970
    return str(year)

def month (hex):
    month = int(hex[2:4], 16)
    if month == 0:
        month = "January"
        return month
    elif month == 1:
        month = "February"
        return month
    elif month == 2:
        month = "March"
        return month
    elif month == 3:
        month = "April"
        return month
    elif month == 4:
        month = "May"
        return month
    elif month == 5:
        month = "June"
        return month
    elif month == 6:
        month = "July"
        return month
    elif month == 7:
        month = "August"
        return month
    elif month == 8:
        month = "September"
        return month
    elif month == 9:
        month = "October"
        return month
    elif month == 10:
        month = "November"
        return month
    else:
        month = "December"
        return month

def day (hex):
    day = int(hex[4:6], 16)
    return str(day)

def hour (hex):
    hour = int(hex[6:8], 16)
    if hour < 10:
        return "0" + str(hour)
    else:
        return str(hour)

def minute (hex):
    minute = int(hex[8:10], 16)
    if minute < 10:
        return "0" + str(minute)
    else:
        return str(minute)

def second (hex):
    second = int(hex[10:12], 16)
    if minute < 10:
        return "0" + str(second)
    else:
        return str(second)

当我使用在线python解释器运行它时,功能正常。我只是不知道如何从命令行运行它并将输出发送回命令窗口。感谢

2 个答案:

答案 0 :(得分:1)

将行sys.stdout.write ...放在函数定义之后。

请不要在函数内使用month作为函数和变量。

答案 1 :(得分:1)

在python中,文件从上到下逐行解析,因此函数monthyearhourminutesecond是尚未定义此行:

sys.stdout.write (month(hex) + " " + day(hex) + ", " + year(hex) + " " + hour(hex) + ":" + minute(hex) + ":" + second(hex))

将这些函数定义移到此行之上。

使用与函数名同名的局部变量不是一个好主意。

由于sys.argv返回一个列表(第一个元素是文件名),因此您无法对其应用hex。对列表中的项目应用hex,即hex( int(sys.argv[1]) )

>>> lis = ['foo.py', '12']
>>> hex( int(lis[1]) )    #use `int()` as hex expects a number
'0xc'