多次执行python脚本


问题内容

我不确定执行此操作的最佳方法,但我将python脚本另存为.py。该脚本的最终输出是两个文件x1.txt和y1.txt。

基本上,我想运行该脚本说1000次,每次运行都用新名称(即x1.txt + y1.txt)写入两个文本文件,然后第二次运行x2.txt和y2.txt。

考虑到这一点,似乎最好使用类似以下的内容来启动整个脚本

runs=xrange(:999)
for i in runs:

##run the script

然后完成一些事情

    for i in runs:
        filnameA=prefix += "a"+i


open("filnamea.txt", "w").write('\n'.join('\t'.join(x for x in g if x) for g in grouper(7, values)))


    for i in runs:
        filnameB=prefix += "a"+i


open("filnameB.txt", "w").write('\n'.join('\t'.join(x for x in g if x) for g in grouper(7, values)))

这真的是最好的方法吗?我敢打赌它不是..更好的主意?

我知道您可以import time写一个可以计算时间的文件名,但这对于以后的处理很烦人。


问题答案:

如果您的计算机具有并行运行这些资源的资源,则可以使用multiprocessing它来做。否则,请使用循环按顺序执行它们。

您对停留在哪个部分的问题不是很明确。您是否需要使用循环的建议?如果是,我的答案在上面。还是在形成文件名时还需要帮助?您可以执行以下操作:

import sys

def myscript(iteration_number):
    xfile_name = "x%d.txt" % iteration_number
    yfile_name = "y%d.txt" % iteration_number
    with open(xfile_name, "w") as xf:
        with open(yfile_name, "w") as yf:
            ... whatever your script does goes here

def main(unused_command_line_args):
    for i in xrange(1000):
        myscript(i)
    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv))