Answer
让我们把它分解成碎片。尤其是那些你做错的部分。 :)
任务
outfile=ReadsAgain.txt
毫不奇怪,您需要在字符串周围加上引号。另一方面,你可以在周围放置空间。=
为了可读性。
outfilename = "ReadsAgain.txt"
变量扩展 →str.format http://docs.python.org/library/stdtypes.html#str.format(或者% http://docs.python.org/library/stdtypes.html#string-formatting-operations手术)
python reads.py <snip/> -q$queries <snip/>
现在您已经知道如何进行重定向了,但是如何进行变量扩展呢?您可以使用the format method http://docs.python.org/library/stdtypes.html#str.format(v2.6+):
command = "python reads.py -r1 -pquery1.sql -q{0} -shotelspec -k6 -a5".format(queries)
您也可以使用the %操作员 http://docs.python.org/library/stdtypes.html#string-formatting-operations:
#since queries is a number, use %d as a placeholder
command = "python reads.py -r1 -pquery1.sql -q%d -shotelspec -k6 -a5" % queries
C 型循环 →面向对象风格的循环 http://docs.python.org/tutorial/controlflow.html#for-statements
for ((r = 1; r < ($runs + 1); r++)) do done
Python 中的循环与 C 风格的迭代不同。 Python 中发生的情况是迭代可迭代对象,例如列表。在这里,你正在尝试做某事runs
次,所以你会这样做:
for r in range(runs):
#loop body here
range(runs)
相当于[0,1,...,runs-1]
, 的列表runs = 5
整数元素。所以你会重复身体runs
次。在每个周期,r
被分配列表的下一项。因此,这与您在 Bash 中所做的完全等同。
如果您感觉大胆,请使用xrange http://docs.python.org/library/functions.html#xrange反而。它完全等价,但使用更高级的语言功能(因此更难用外行术语解释),但消耗的资源更少。
输出重定向 →the subprocess module http://docs.python.org/library/subprocess.html?highlight=subprocess#using-the-subprocess-module
如果您愿意的话,“更难”的部分是:执行程序并获取其输出。谷歌来救援! http://www.google.com/search?q=how+to+get+the+output+of+a+program+python显然,最热门的是一个 stackoverflow 问题:this one https://stackoverflow.com/questions/748028/how-to-get-output-of-exe-in-python-script。您可以使用一个简单的函数隐藏其背后的所有复杂性:
import subprocess, shlex
def get_output_of(command):
args = shlex.split(command)
return subprocess.Popen(args,
stdout=subprocess.PIPE).communicate()[0]
# this only returns stdout
So:
python reads.py -r1 -pquery1.sql -q$queries -shotelspec -k6 -a5 >> $outfile
becomes:
command = "python reads.py -r1 -pquery1.sql -q%s -shotelspec -k6 -a5" % queries
read_result = get_output_of(command)
不要过度-subprocess
, 包括电池
或者,考虑一下您可以获得几乎相同的输出date
具有以下内容:
import time
time_now = time.strftime("%c", time.localtime()) # Sat May 15 15:42:47 2010
(请注意缺少时区信息。这应该是另一个问题 https://stackoverflow.com/questions/ask,如果这对您很重要。)
你的程序应该是什么样子
最终结果应如下所示:
import subprocess, shlex, time
def get_output_of(command):
#... body of get_output_of
#... more functions ...
if __name__ = "__main__":
#only execute the following if you are calling this .py file directly,
#and not, say, importing it
#... initialization ...
with file("outputfile.txt", "a") as output_file: #alternative way to open files, v2.5+
#... write date and other stuff ...
for r in range(runs):
#... loop body here ...
后经文
与相对简单且简短的 Bash 脚本相比,这看起来一定非常可怕,对吧? Python 不是一种专门的语言:它的目标是把所有事情都做得相当好,但并不是直接为运行程序和获取程序的输出而构建的。
尽管如此,你还是不会normally用 Bash 写一个数据库引擎,对吧?不同的工作有不同的工具。在这里,除非您计划进行一些使用该语言编写的不简单的更改,否则 [Ba]sh 绝对是正确的选择。