多次执行python脚本 [英] execute python script multiple times
问题描述
我不确定这样做的最佳方法,但我有一个保存为 .py 的 python 脚本.这个脚本的最终输出是两个文件 x1.txt 和 y1.txt.
Im not sure about the best way to do this but I have a python script saved as a .py. The final output of this script is two files x1.txt and y1.txt.
基本上我想运行这个脚本 1000 次,每次运行用新名称写入我的两个文本文件,即 x1.txt + y1.txt 然后第二次运行 x2.txt 和 y2.txt.
Basically I want to run this script say 1000 times and each run write my two text files with new names i.e x1.txt + y1.txt then second run x2.txt and y2.txt.
考虑到这一点,似乎用类似的东西开始整个脚本可能会更好
Thinking about this it seems it might be better to start the whole script with something like
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)))
这真的是最好的方法吗?我敢打赌它不是……更好的想法?
Is this really the best way to do it? I bet its not..better ideas?
我知道您可以导入时间
并编写一个可以计算时间的文件名,但这在以后处理时会很烦人.
I know you can import time
and write a filename that mathes time but this would be annoying for processing later.
推荐答案
如果您的计算机具有并行运行这些的资源,您可以使用 multiprocessing
来实现.否则使用循环顺序执行它们.
If your computer has the resources to run these in parallel, you can use multiprocessing
to do it. Otherwise use a loop to execute them sequentially.
你的问题不是很明确你被困在哪个部分.您是否只需要有关是否应该使用循环的建议?如果是的话,我的答案就在上面.或者您还需要有关形成文件名的帮助吗?你可以这样做:
Your question isn't quite explicit about which part you're stuck with. Do you just need advice about whether you should use a loop? If yes, my answer is above. Or do you also need help with forming the filenames? You can do that part like this:
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))
这篇关于多次执行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!