繁体   English   中英

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

[英]How to run an argv script from Mac OSX terminal

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

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

布赖恩

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

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

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

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM