Python 2.7 NameError:

时间:2015-11-17 22:01:05

标签: python python-2.7

我是Python编码的新手,并且一直在研究这段代码,而我似乎无法解决这个问题。

我有这段代码:

from sys import argv

argv = script, user_name
prompt = '> '

print "Hi their %s!  I am the %s script!" % (user_name, script)
print "I would like to ask you a few questions about yourself."
print "Do you think that computers can rise up against humans %s?" % user_name
computer_rise = raw_input(prompt)

print "Do you think that its possible I will rise up against you %s?" % user_name
i_will_rise = raw_input(prompt)

print """
Alright so you said %s that computers can rise up against humans.
And you said that you think %s it is possible I will rise up against you.
You should be ashamed of yourself for having such a crazy irrational mind.
Go worry about ISIS or something else you nymph!
""" % (computer_rise, i_will_rise)

当我把它输入python时我得到了这个错误

Macintosh:python eileen$ python raw_inputargvex2.py Greg
Traceback (most recent call last):
  File "raw_inputargvex2.py", line 3, in <module>
    argv = script, user_name
NameError: name 'script' is not defined

如何解决此未定义的脚本问题?

3 个答案:

答案 0 :(得分:3)

来自sys import argv

argv = script, user_name

更改此

script = argv[1]
user_name = argv[2]

到这个

www.example.com/chat

问候! 纳尔逊。

答案 1 :(得分:2)

改变这个:

argv = script, user_name

对此:

script = argv[0]
user_name = argv[1]

或者这个:

script, user_name = argv

如果用户没有提供足够的参数,或者太多,例如:

,您可能还想做某些事情
if len(argv) < 2:
    print "I need moar arguments, please supply a user name"
    quit(1)
elif len(argv) > 2:
    print "I don't need so many arguments, you are making my head hurt"
    quit(1)

答案 2 :(得分:0)

查看你的代码,看起来你想让argv [1](在命令行上传递的第一个参数,argv [0]是你正在运行的代码的名称)到脚本变量

所以:

script = argv[1]
user_name = argv[2]

这应解决该特定问题。