初学python,写了一段脚本:
from sys import argv
script,user_name=argv
prompt='<'
print("hi %s,i am the %s script."%(user_name,script))
print("I'd like to ask you a few questions.")
print("DO you like me %s"%user_name)
input(prompt)
在Pycharm上面运行会出现如下错误:
D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/untitled/ex14.py
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/ex14.py", line 2, in
script,user_name=argv
ValueError: not enough values to unpack (expected 2, got 1)
Process finished with exit code 1
这是什么原因,用cmd运行就没有问题,可以出来结果
from sys import argv
script=argv
user_name=argv
prompt='<'
print("hi %s,i am the %s script."%(user_name,script))
print("I'd like to ask you a few questions.")
print("DO you like me %s"%user_name)
input(prompt)
分开写就可以了
我觉得应该是这样:
argv指的是命令行的参数,比如你在命令行运行某程序:python test.py ,这个命令行的参数就是test.py。
也就是说命令行第一个参数默认就是py文件名,在你这个程序中就是script参数的值,编辑器运行程序就相当于只带一个参数运行,没有显示指明,就是该文件名。
而在cmd中你是可以带多个参数:
>python test.py jack
hi jack,i am the test.py script.
I'd like to ask you a few questions.
DO you like me jack
<
这里就带上了user_name参数的值jack,而在编辑器中参数只有一个,编辑器的默认工作方式是python test.py
修改如下:
from sys import argv
user_name = input("please tell me your name:")
argv = user_name
prompt='<'
print("hi %s,i am the %s script."%(user_name, __file__))
print("I'd like to ask you a few questions.")
print("DO you like me %s"%user_name)
input(prompt)
这样就可以在编辑器里运行了。