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

标签 python pycharm

我开始通过 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相反

关于python - 使用 PyCharm 编写脚本参数 - Learn Python the Hard way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858503/

相关文章:

python - Tweepy 流媒体过滤器字段

python - pycharm 代码自动完成不适用于带有 ipython 的 python 控制台

python - 如何让 PyC​​harm 在其控制台中显示 unicode 数据?

python - Pycharm 是否有文档字符串约定检查(PEP 257)?

python - Pycharm 与使用相等运算符执行的 None 比较

python - 如何在Python中对两个pandas数据框列进行自定义排序?

python - 使用 Python/Pandas 处理嵌套在 JSON 中的 JSON

python - 如何在 OpenCV for Python 中使用冲浪和筛选检测器

python - 将 SQL 转换为 SQL 炼金术

ubuntu - 关于删除pycharm安装包的问题