0

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?

napuzba
  • 6,033
  • 3
  • 21
  • 32
sramij
  • 4,775
  • 5
  • 33
  • 55

1 Answers1

1

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'
napuzba
  • 6,033
  • 3
  • 21
  • 32
  • I don't want to use escapes in the input command, there are more special characters in the extended command that `, is that still possible? – sramij Oct 04 '16 at 18:56
  • It is related to your shell more than python. Try to use ' instead of " – napuzba Oct 04 '16 at 19:07