简体   繁体   中英

Execute Shell Script from python with arguments

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"

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.

为什么不将--nosave保存到变量并在subprocess --nosave中传递变量

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM