如何从Mac OSX终端运行argv脚本

时间:2011-12-03 22:16:51

标签: python macos python-idle

有一个关于在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

我需要输入解释器/终端才能运行此脚本?非常感谢!

布赖恩

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

为了使该脚本有效,您需要在命令行上提供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)

答案 2 :(得分:1)

不幸的是,当从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)