Skip to main content
 首页 » 编程设计

python之使用 PyCharm 编写脚本参数之Learn Python the Hard way

2025年05月04日33telwanggs

我开始通过 learn Python the Hard Way 学习 Python,但我遇到了 ex13 的一些问题。我现在想知道这是我的错误还是因为 PyCharm 的工作方式。

基本上,为了使脚本按照练习建议的方式工作,我必须在 PyCharm 中手动输入参数名称,运行>编辑配置

我把“第一”“第二”和“第三”放在一起

但我想将 raw_input 和 argv 结合起来,这样我就可以让用户选择参数的名称。这是我写的:

from sys import argv 
 
first = raw_input("First argument: ") 
second = raw_input("Second argument: ") 
third = raw_input("Third argument: ") 
 
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 

它运行但返回:

ValueError: need more than 1 value to unpack 

似乎在 PyCharm 中我必须手动输入所有脚本参数?没有办法将它与原始输入结合起来吗?

感谢您的帮助。

请您参考如下方法:

注意查看Joran's答案显示了使用命令行参数和提示用户输入的良好组合。下面是正在发生的事情的分解:

这是 PyCharm 中的预期行为,用于指定您希望 PyCharm 用来执行脚本的参数。把它想象成 PyCharm 做这样的事情:

python my_script.py 

但是,PyCharm 不知道您要传递的参数,您需要提供它,以便它知道如何运行您的脚本。如果您查看 PyCharm 窗口底部附近,会看到一个 Terminal 选项卡。您可以使用它来快速执行脚本并提供参数。

其次,您收到错误的原因是您在尝试使用 argv 时没有正确处理脚本输入。

您混淆了 raw_input 的使用,它在您的 Python 脚本运行时接收用户输入,而 argv 在您运行时接收参数到您的 Python 脚本运行。

因此,您在这里实际要做的不是使用 raw_input,而是简单地使用 argv。这是一个小演示来澄清这一切:

from sys import argv 
 
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 

现在,进入命令提示符并执行以下操作:

python my_script one two three 

您将获得:

The script is called: my_script.py 
Your first variable is: one 
Your second variable is: two 
Your third variable is: three 

这是一个非常简化的示例,您可能需要添加一些输入处理,否则您将因脚本的不同输入而出现很多错误。有了这个,我建议也许看看 argparse相反