Ubuntu – Pass a bash variable to python script

bashcommand linepythonscripts

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".

Best Answer

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
Related Question