0

The command:

make foo -f $*

Has different functionality when called from the command line versus when it is called from a python script as follows:

import os
os.system(make foo -f $*)

As stated here: http://tldp.org/LDP/abs/html/internalvariables.html#APPREF $* in a bat file is basically all the positional parameters seen as a single word.

Python seems to be parsing it as simply "$*". Is there anyway to get around this and replicate the same functionality?

I realise I can write a .bat script and call that with python but I was hoping for something more eloquent.

Shani de Leeuw
  • 171
  • 1
  • 11
  • Forget about `os.system`. Always use the functions from `subprocess` and *avoid* passing `shell=True` as much as possible. – Bakuriu Jul 28 '16 at 09:09

1 Answers1

1

As you point out, $* has no special meaning in python. The comprehension is done entirely by whatever shell you are using. If you want to pass all positional parameters passed to your script to some command, then you can try the following

import os, sys
os.system("make foo -f {}".format(" ".join(sys.argv[1:])))

Please note however that os.system is deprecated. You should probably use

import subprocess, sys
subprocess.check_call("make foo -f {}".format(" ".join(sys.argv[1:])), shell=True)

instead.

Edit

As suggested in the comments, one should avoid using shell=True whenever the command is built from "untrusted" input, such as the command line of the program. Therefore a much better alternative is to use

import subprocess, sys
subprocess.check_call(['make', 'foo', '-f'] + sys.argv[1:])
Mörökölli
  • 116
  • 4
  • 2
    Note that there is no reason to use `shell=True` for doing that. It's simpler to just use `check_call(['make', 'foo', '-f'] + sys.argv[1:])` you even get rid of calling `join`. – Bakuriu Jul 28 '16 at 09:09
  • @Bakuriu beat me to it - no reason to use shell here given the example -it's best to avoid it where possible to avoid potentially "interesting" commands slipping through – Jon Clements Jul 28 '16 at 09:10
  • @JonClements Or vulnerabilities like SHELLSHOCK which can be triggered even if you have complete control over the command but you let the shell inherit your environment... – Bakuriu Jul 28 '16 at 09:14