0

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

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 解释器运行它时,函数运行良好。我只是不知道如何从命令行运行它并将输出发送回命令窗口。谢谢

4

2 回答 2

1

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

请不要month同时用于您的函数和该函数内的变量。

于 2013-05-29T14:55:58.440 回答
1

在 python 中,文件是从上到下逐行解析的,因此该行尚未定义函数monthyear、和:hourminutesecond

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

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

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

Assys.argv返回一个列表(第一个元素是文件名),所以你不能应用hex它。适用hex于列表的项目,即hex( int(sys.argv[1]) )

>>> lis = ['foo.py', '12']
>>> hex( int(lis[1]) )    #use `int()` as hex expects a number
'0xc'
于 2013-05-29T14:56:42.690 回答