I want to execute a shell script with 3 arguments from a python script. (as described here: Python: executing shell script with arguments(variable), but argument is not read in shell script)
Here is my code:
subprocess.call('/root/bin/xen-limit %s %s %s' % (str(dom),str(result),str('--nosave'),), shell=True)
variables dom and result are containing strings.
And here is the output:
/bin/sh: --nosave: not found
UPDATE:
That is the variable "result":
c1 = ['/bin/cat', '/etc/xen/%s.cfg' % (str(dom))]
p1 = subprocess.Popen(c1, stdout=subprocess.PIPE)
c2 = ['grep', 'limited']
p2 = subprocess.Popen(c2, stdin=p1.stdout, stdout=subprocess.PIPE)
c3 = ['cut', '-d=', '-f2']
p3 = subprocess.Popen(c3, stdin=p2.stdout, stdout=subprocess.PIPE)
c4 = ['tr', '-d', '\"']
p4 = subprocess.Popen(c4, stdin=p3.stdout, stdout=subprocess.PIPE)
result = p4.stdout.read()
After that, the variable result is containing a number with mbit (for example 16mbit)
And dom is a string like "myserver"
3 Answers 3
from subprocess import Popen, STDOUT, PIPE
print('Executing: /root/bin/xen-limit ' + str(dom) + ' ' + str(result) + ' --nosave')
handle = Popen('/root/bin/xen-limit ' + str(dom) + ' ' + str(result) + ' --nosave', shell=True, stdout=PIPE, stderr=STDOUT, stdin=PIPE)
print(handle.stdout.read())
If this doesn't work i honestly don't know what would. This is the most basic but yet error describing way of opening a 3:d party application or script while still giving you the debug you need.
4 Comments
Executing: /root/bin/xen-limit test1 016mbit --nosave But --nosave is on a new line.. And I get the same error (--nosave not found)print([str(dom), str(result)]), something tells me you just have a \n in the string somewhere that you forgot to parse out.[..] list and you'll see any inconsistencies which might affect your outcome, tl;dr: It helps you analyze your data :) Glad it fixed it and GL with your endeavors ;)Why not you save --nosave to a variable and pass the variable in subprocess
2 Comments
It's simpler (and safer) to pass a list consisting of the command name and its arguments.
subprocess.call(['/root/bin/xen-limit]',
str(dom),
str(result),
str('--nosave')
])
str('--nosave') is a no-op, as '--nosave' is already a string. The same may be true for dom and result as well.
subprocess.call('/root/bin/xen-limit %s %s %s' % (str(dom),str(result),'--nosave'), shell=True)?result? It sounds like it contains some shell metacharacter which terminates a command, making--nosavelook like a second command instead of an option toxen-limit.--nosavefirst, do you get the same error? What do you mean "echo the 3 parameters" in the comment below?