4

I'd like to experiment codes from command line, so import argv form 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.

How can pass an array as argument?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 2
    Possible duplicate of [How to pass an array to python through command line](https://stackoverflow.com/questions/36926077/how-to-pass-an-array-to-python-through-command-line) – Pedro Lobito Apr 08 '18 at 00:36

2 Answers2

2

There are a couple different ways you can do this...

using 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()

You can also use exec() which may be more risky and complicated. 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
Taylor Iserman
  • 175
  • 1
  • 16
1

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.

Additionally, module argparse helps

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138