将python变量传递给命令

时间:2015-10-29 11:15:15

标签: python shell command

我想传递变量'首先'并且'最后'从我的python片段到命令。

Python代码:

import csv
import dateutil.parser

with open('run.csv') as f:
   reader = csv.reader(f)
   first = dateutil.parser.parse(reader.next()[3])
   for row in reader:
     pass
last = dateutil.parser.parse(row[3])

命令:

$ influx -execute="SELECT MEAN(value) FROM cpu_value WHERE time >= first and time <= last GROUP BY type,type_instance" -database=collectd  -format=csv -pretty=true 

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

你应该最好从python中调用涌入。 为此,您可以使用python&#39; s subprocess.check_call。见here

import csv
import dateutil.parser
import subprocess

with open('run.csv') as f:
   reader = csv.reader(f)
   first = dateutil.parser.parse(reader.next()[3])
   for row in reader:
      pass
last = dateutil.parser.parse(row[3])

print (first,last)
command = "/opt/influxdb/influx -execute=\"SELECT MEAN(value) FROM cpu_value WHERE time >= {0} and time <= {1} GROUP BY type,type_instance\" -database=collectd  -format=csv -pretty=true".format(first, last)subprocess.check_call(command, shell=True)