Getting function as string then run it

I have script like:

from string import digits, uppercase, lowercase, punctuation
from itertools import product

chars = lowercase + uppercase + digits + punctuation

for n in range(1,  2+1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

it works fine. Imagine chars is giving by an external user so:

import sys
from string import digits, uppercase, lowercase, punctuation
from itertools import product

chars = sys.argv[1] # sys.argv[1] is 'lowercase+uppercase+digits+punctuation'

for n in range(1,  2+1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

when run script.py: It has not the result when you say:

chars = lowercase + uppercase + digits + punctuation

Now how can I get the previous result?

Answers


You can use a dictionary mapping the user input to the corresponding strings.

>>> input_to_chars = {
...     'lowercase': lowercase,
...     'uppercase': uppercase,
...     'digits': digits,
...     'punctuation': punctuation
... }

Construct chars from the user input like this:

>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(input_to_chars[i] for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

Or with the hint from @schwobaseggl in the comments:

>>> import string
>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(getattr(string, i) for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

The dictionary solution is easy to extend, the getattr solution is good if you don't want to extend your program to accept user inputs which are not attributes of string.


Need Your Help

MySQL gett rows from last week with their day name

mysql sql

I am having trouble with a query. This is taken from a similar query where i count number of rows per month.

Expression blend 4 Silverlight version Incompatibility

silverlight version expression-blend incompatibility

I am getting the below error when I try create new sketch flow application