Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a range in command line arguments
#1
i have written a script that gets one or more numeric values on a command line (ultimately from sys.argv). i would like to include an ability to let the user give a range a have the script work the same as if that range's numbers were typed in. i have tried a couple of ways to do this. one of them was to run each argument through eval() and work with the results. if the result was an int, it was just collected into the list of ints. otherwise the result was run through list() and if that succeeded, that list was concatenated to the list of ints. that allowed the user to use a range() call or any other call that created an iterator. the other method i tried was to see if the argument had a ":" in it. if so, then it was split(":") and if the result was length 2 or 3, it was fed to range() as 2 or 3 arguments. a disadvantage to this was that it did not provide a means to give range() just one argument. it also did not provide a means to call other functions.

which of these should i use or do you have another idea?
Skaaaaaperen........
Quote
#2
You could parse the argument with module ast
>>> import ast
>>> def extract(stuff):
...     for node in ast.walk(stuff):
...         if isinstance(node, ast.Num):
...             yield node.n
... 
>>> list(extract(ast.parse( 'range(3, 5)' )))
[3, 5]
>>> list(extract(ast.parse( 'range(3)' )))
[3]
>>> list(extract(ast.parse( '3' )))
[3]
See this doc for example.
Quote
#3
i don't want to require the user to have to type the arg in as list(extract(ast.parse( 'range(3, 5)' ))) when they want the numbers produced by range(3, 5).
Skaaaaaperen........
Quote
#4
I mean that the users can write range(3, 5) but your code can parse the expression by using ast.parse() and produce the list [3, 4]. The code could traverse the abstract syntax tree to see if the expression entered by the user belongs to a set of allowed expression. That way, you can have the effect of eval() without the risks.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  command line progam wanted: clock Skaperen 2 269 Apr-18-2018, 06:54 AM
Last Post: Gribouillis

Forum Jump:


Users browsing this thread: 1 Guest(s)