如何在Spyder中使用argv

问题描述 投票:9回答:4

我在Spyder中运行下面的代码。我在py文件中输入了它,只需点击运行按钮即可。

当我尝试运行它时,我收到错误:

ValueError:需要多于1个值才能解压缩

如图所示,你打算在运行程序之前给出argv变量的输入,但我不知道如何做到这一点是spyder?

http://learnpythonthehardway.org/book/ex13.html

from sys import argv

script, first, second, third = argv

print "The script is called:", script
print "The first variable is:", first
print "The second variable is:", second
print "Your third variable is:", third
python spyder
4个回答
-7
投票

阅读页面底部的常见问题解答,它特别提到了这个错误。

常见的学生问题

问:当我运行它时,我得到了ValueError: need more than 1 value to unpack

请记住,一项重要技能是关注细节。如果查看“应该看到的内容”部分,您会看到我在命令行上使用参数运行脚本。你应该复制我完全运行它的方式。

确保运行命令:

$ python ex13.py first 2nd 3rd
>> The script is called: ex13.py  
>> Your first variable is: first  
>> Your second variable is: 2nd  
>> Your third variable is: 3rd

您可以确保提供参数。

if __name__ == '__main__':
    if len(argv) == 4:
        script, first, second, third = argv

        print 'The script is called:', script
        print 'Your first variable is:', first
        print 'Your second variable is:', second
        print 'Your third variable is:', third
    else:
        print 'You forgot the args...'

36
投票

要将argv传递给Spyder中的脚本,您需要进入菜单项

Run > Configuration per file

或者按Ctrl + F6键,然后查找名为的选项

Command line options

在此之后出现的对话框中,最后输入要传递给脚本的命令行参数,在这种情况下可以是

one two three


9
投票

在Spyder中,去Run > Configure并定义你的argv值,如下图所示,并运行脚本只需按F6


4
投票

除了在Run->Configure中配置,如其他答案中所述,您可以直接从控制台使用“runfile”。

运行以下命令:

   runfile('ex13.py', args='first second third')
© www.soinside.com 2019 - 2024. All rights reserved.