13

I have this python script:

#!/usr/bin/env python
def getPermutation(s, prefix=''):
        if len(s) == 0:
                print prefix
        for i in range(len(s)):
                getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )



getPermutation('abcd','')

However, I want to be able to call this script using a variable for "abcd" so I can insert any combination of letters instead of "abcd" like "efgh" for example.

Normally, I can use a $@ or $1 instead of abcd on the last line in a bash script like this:

#!/usr/bin/env python
def getPermutation(s, prefix=''):
        if len(s) == 0:
                print prefix
        for i in range(len(s)):
                getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )



getPermutation("$1",'')

But when I run the script using something like ./scriptname.py efgh I get:

$1
1$

instead of the permutations for "efgh".

22

The python equivalent of the shell's positional parameter array $1, $2 etc. is sys.argv

So:

#!/usr/bin/env python

import sys

def getPermutation(s, prefix=''):
        if len(s) == 0:
                print prefix
        for i in range(len(s)):
                getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )



getPermutation(sys.argv[1],'')

then

$ ./foo.py abcd
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba
7

Lots of ways to parameterize python. positional args, env variables, and named args. Env variables:

import os and use the getenv like:

fw_main_width  =os.getenv('FW_MAIN_WIDTH',  fw_main_width)  

Where the second parameter is the default for the env variable not being set.

Positional args:

Use the sys.argc, sys.argv[n] after you import sys.

Named parameters:

Or for named parameters,(what you asked)

 import argparse  

then describe the possible parameters:

parser = argparse.ArgumentParser(description = "Project", fromfile_prefix_chars='@')
parser.add_argument("-V", "--version", help="show program version", action="store_true")
parser.add_argument("-W", "--width", help="set main screen width")  
read arguments from the command line  

args = parser.parse_args()

and use them as args.width etc.

  • I didn't really understand this at first but this really helps explain the accepted answer and now it makes more sense. Thanks! – mchid Oct 7 at 1:16
2

Okay, I figured out a workaround while I was writing the question but I felt that this would useful to other users so here it is.

For python (python2), we can use raw_input() instead of $1 but it works a bit differently. Instead of entering the input after the script name in bash, you are prompted to input the value after you run the script.

Here is an example:

#!/usr/bin/env python
def getPermutation(s, prefix=''):
        if len(s) == 0:
                print prefix
        for i in range(len(s)):
                getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i] )



getPermutation(raw_input("enter characters: "),'')

Running the script will prompt the user to "enter characters:". After the user enters the characters and then presses ENTER, the permutations will print in the terminal.

Here is the source which also explains how to do this for python3.

  • This might 'work' for you, but you're not actually answering your own question, which is about passing a variable ;) – djsmiley2k - CoW Oct 6 at 19:18
  • @djsmiley2k Yes, it's a workaround. That's why I accepted the other answer as the solution. – mchid Oct 6 at 19:57
  • 2
    Meanwhile Python 2 gets deprecated – Kulfy Oct 7 at 14:26
  • @Kulfy I used python2 because it is the system default for python on 18.04. I've had to use python3 for maths in the past because python2 likes to round the numbers. Thanks for the heads up! – mchid Oct 8 at 22:48
1
import itertools, argparse

def main():
        parser = argparse.ArgumentParser()
        parser.add_argument('-l', '--letters', dest='letters',  type=str, help='Letters to iterate over')
        options = parser.parse_args()


        a = [''.join(i) for i in itertools.permutations(options.letters)]
        print(a)

if __name__ == '__main__': main()

On the command line: FileName.py -l abcd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.