I am a beginner trying to get a shell command from a user in Pyramid and pass it to subprocess.check_output["thisisthecommand"]
The variable is stored in myvar. Eg:myvar="echo helloworld" How to pass this variable inside my subprocess check_output?
I tried doing this subprocess.check_output[myvar] but it doesnt work. Pyramid throws the error 'AttributeError:NoneType object has no attribute' Please help.
As per the documentation (and the examples therein) you need to separate command and arguments in the list. e.g,
subprocess.check_output(['echo', 'hello'])
should work. There is a shell
option which would allow you to write subprocess.check_output('echo hello', shell=True)
but that is best left alone for security reasons.
If you use a variable myvar
containing the command, you can use shlex.split()
to produce a list suitable for passing to check_output()
:
import shlex, subprocess
myvar = 'echo hello'
args = shlex.split(myvar)
output = subprocess.check_output(args)
>>> args
['echo', 'hello']
Incidentally, Python functions are invoked using using ()
, not []
- the latter used for indexing a sequence or accessing a dictionary by key.