简体   繁体   English

将数组作为命令行参数传递给脚本

[英]Pass an array as command line argument to the script

I'd like to experiment codes from command line, so import argv form sys . 我想从命令行实验代码,所以导入argv表单sys

    from sys import argv
    def binary_search(array, item):
        low = 0
        high = len(array) - 1
        while low <= high:
            mid = (low + high) // 2 # round down if not an even 
            guess = array[mid]
            if guess == item:
                return mid
            if guess > item:
                high = mid - 1
            else:
                low = mid + 1
        return None

    def main():
        script, array, item = argv
        binary_search(array, item)

When run it on the command line: 在命令行上运行时:

    $ python3 binary_search.py [1, 2, 3] 8
    Traceback (most recent call last):  File "binary_search.py", line 94, in <module>
        main()  File "binary_search.py", line 89, in main
        script, array, item = argvValueError: too many values to unpack (expected 3)

I tested and found that arguments passed from command line are treated as str by argv. 我测试并发现从命令行传递的参数被argv视为str。

How can pass an array as argument? 如何将数组作为参数传递?

There are a couple different ways you can do this... 有几种不同的方法可以做到这一点......

using re 使用re

Using regular expressions may be one of the easiest ways of handling this. 使用正则表达式可能是处理此问题的最简单方法之一。

from sys import argv
import re

def binary_search(array, item):
    low = 0
    high = len(array) - 1
    while low <= high:
        mid = (low + high) // 2 # round down if not an even 
        guess = array[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

def main():
    array = re.findall(r"[\w]+", argv[1])
    array = [int(i) for i in array]
    item = int(argv[2])

    binary_search(array,item)


if __name__== "__main__":
    main()

using exec() 使用exec()

You can also use exec() which may be more risky and complicated. 你也可以使用exec() ,这可能更危险和复杂。 Here's a simple example: 这是一个简单的例子:

from sys import argv

command = 'mylist = {0}'.format(argv[1])

exec(command)

for item in mylist:
    print(item)

example output: 示例输出:

C:\path>py foo.py [1,2,3]
1
2
3

The arguments on the command line are strings, they're not parsed like literals in the program. 命令行上的参数是字符串,它们不像程序中的文字那样被解析。

argv construct the strings automatically to a list from command line arguments (as separated by spaces), in short, sys.argv is a list. argv从命令行参数自动构造字符串到列表(由空格分隔),简而言之, sys.argv是一个列表。

Additionally, module argparse helps 另外,模块argparse有帮助

The argparse module makes it easy to write user-friendly command-line interfaces. argparse模块可以轻松编写用户友好的命令行界面。 The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. 程序定义了它需要的参数,argparse将弄清楚如何解析sys.argv中的参数。 The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments. 当用户给程序提供无效参数时,argparse模块还会自动生成帮助和使用消息并发出错误。

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

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