【问题标题】:execute python script multiple times多次执行python脚本
【发布时间】:2012-04-25 08:56:47
【问题描述】:

我不确定执行此操作的最佳方法,但我有一个保存为 .py 的 python 脚本。该脚本的最终输出是两个文件 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 并写一个计算时间的文件名,但这对于以后的处理来说会很烦人。

【问题讨论】:

  • 您运行脚本 1000 次,然后您将结果写入 1000 次到 2 个文件中的每一个? EACH 是否应该在开始下一个之前运行写入自己的输出文件?
  • 每次运行写入两个文件。我明白你的意思。

标签: python python-2.7


【解决方案1】:

如果您的计算机具有并行运行这些资源的资源,您可以使用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))

【讨论】:

    【解决方案2】:

    我不确定,但也许会有所帮助: 假设,我想打印 'hello' 10 次,而不是手动写 10 次。为此,我可以定义一个函数:

        #Function for printing hello 10 times:
        def func(x):
           x="hello"
           i=1
           while i<10 :
               print(x)
               i += 1
           else :
               print(x)
    
        
        print(func(1))
    

    【讨论】:

      【解决方案3】:
      import subprocess
      import sys
      
      script_name = 'dummy_file.py'
      output_prefix = 'out'
      n_iter = 5
      
      for i in range(n_iter):
          output_file = output_prefix + '_' + str(i) + '.txt'
          sys.stdout = open(output_file, 'w')
          subprocess.call(['python', script_name], stdout=sys.stdout, stderr=subprocess.STDOUT)
      

      运行此程序时,您将获得 5 个输出文本文件(out_0.txt、...、out_4.txt)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-21
        • 2018-09-06
        • 2015-07-08
        • 2020-08-18
        • 2014-06-09
        • 2017-06-29
        相关资源
        最近更新 更多