【问题标题】:How to run an argv script from Mac OSX terminal如何从 Mac OSX 终端运行 argv 脚本
【发布时间】:2011-12-03 22:16:51
【问题描述】:

有一个关于在 Python 中运行脚本的快速问题。我在保存为“ex13.py”的文件中输入了以下代码:


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

当我尝试从 IDLE 的下拉菜单中简单地“运行”它时,它给了我这个错误:


Traceback (most recent call last):
  File "/Users/brianerke 2/Desktop/ex13.py", line 3, in <module>
    script, first, second, third = argv
ValueError: need more than 1 value to unpack

我需要在解释器/终端中输入什么来运行这个脚本?非常感谢!

布赖恩

【问题讨论】:

  • 请参阅this question,了解有关将命令行参数传递给要在 IDLE 中运行的脚本的信息。
  • 那里描述的方法在 Python 的标准 OS X 安装上不太适用,因为 IDLE 不是以这种方式安装的,即它只是作为 idle 安装的。但 IDLE 通常在 OS X 上通过双击图标来启动。

标签: python macos python-idle


【解决方案1】:

如果你想从终端运行,你会写

python Desktop/ex13.py 1 2 3

假设您在主文件夹中并且想要传递参数 1、2 和 3。

但是,您的打印行似乎无效,将打印件分隔为单独的行

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 work/t.py 1 2 3
The script is called: work/t.py
Your first variable is: 1
Your second variable is: 2
Your third variable is: 3

【讨论】:

    【解决方案2】:

    为了使该脚本正常工作,您需要在命令行上提供 3 个位置参数。

    python /Users/brianerke 2/Desktop/ex13.py option1 option2 option3
    

    为避免错误,您可以检查argv的长度:

    if len(sys.argv) < 3:
        print "You must supply three arguements"
        sys.exit(1)
    

    【讨论】:

      【解决方案3】:

      不幸的是,在从 OS X 版本的 IDLE 中运行 Python 脚本时,没有一种简单的方法可以直接提供参数。正如其他人指出的那样,最简单的解决方案是在 IDLE 中编辑,保存脚本,然后使用 Terminal.app 使用 python 命令从终端会话窗口中直接运行脚本。

      另一种方法是添加一些脚手架代码以允许您模拟传递命令行参数。一个简单(但不是最好的)示例:

      from sys import argv
      
      def main(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
      
      if __name__ == '__main__':
          if len(argv) < 4:
              argv = ['script', '1', '2', '3']
          main(argv)
      

      【讨论】:

        猜你喜欢
        • 2017-11-04
        • 2018-01-08
        • 2012-04-18
        • 2020-11-27
        • 2021-07-31
        • 1970-01-01
        • 2011-05-06
        • 2020-04-01
        • 2011-08-17
        相关资源
        最近更新 更多