【问题标题】:Python output to command line; Error not definedPython 输出到命令行;错误未定义
【发布时间】:2013-05-29 14:51:55
【问题描述】:

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

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

【问题讨论】:

  • 不要使用与函数相同的变量名。

标签: python function command-line output


【解决方案1】:

在python中,文件是从上到下逐行解析的,所以函数month,year,hour,minutesecond还没有为这一行定义:

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'

【讨论】:

    【解决方案2】:

    在你的函数定义之后添加sys.stdout.write...行。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-08
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多