[英]Execute Shell Script from python with arguments
我想用python脚本中的3个参数执行shell脚本。 (如下所述: Python:使用参数(变量)执行shell脚本,但在shell脚本中不读取参数 )
这是我的代码:
subprocess.call('/root/bin/xen-limit %s %s %s' % (str(dom),str(result),str('--nosave'),), shell=True)
变量dom和result包含字符串。
这是输出:
/bin/sh: --nosave: not found
更新:
这是变量“结果”:
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()
之后,变量结果包含一个mbit的数字(例如16mbit)
而dom是一个像“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())
如果这不起作用我老实说不知道会是什么。 这是打开3:d方应用程序或脚本的最基本但却错误的描述方式,同时仍然为您提供所需的调试。
为什么不将--nosave
保存到变量并在subprocess
--nosave
中传递变量
传递由命令名及其参数组成的列表更简单(也更安全)。
subprocess.call(['/root/bin/xen-limit]',
str(dom),
str(result),
str('--nosave')
])
str('--nosave')
是一个无操作,因为'--nosave'
已经是一个字符串。 dom
和result
也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.