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".
The python equivalent of the shell's positional parameter array
$1
,$2
etc. issys.argv
So:
then
Lots of ways to parameterize python. positional args, env variables, and named args. Env variables:
import os and use the getenv like:
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)
then describe the possible parameters:
and use them as args.width etc.
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:
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.
On the command line: FileName.py -l abcd