pythonshelloptionparser

Receive a shell command as an OptionParser string argument


I am using OptionParser(), and define the following:

parser.add_option("--cmd", dest="command", help="command to run")

However, if i provide a complex shell command, such as :

python shell.py --cmd "for i in `seq 1 10`; do xxx; done"

And internally print options.command, i get something unexpected to me:

for i in 1
2
3
4
5
6
7
8
9
10; do

Is there a good way to pass an OptionParser option which is a shell command?


Solution

  • When invoking:

    python shell.py --cmd "for i in `seq 1 10`; do xxx; done"
    

    The shell first substitute the command enclosed in ` with its output. Thus, the command you actually invoke is:

    python shell.py --cmd "for i in 1
    2
    3
    4
    5
    6
    7
    8
    9
    10; do ..."
    

    To avoid this:

    Escape the ` character when invoking the command:

    python shell.py --cmd "for i in \`seq 1 10\`; do xxx; done"
    

    Use strong quoting (string enclosed in ')

    python shell.py --cmd 'for i in `seq 1 10`; do xxx; done'