我想要创建一个python文件,该文件创建一个自身的副本,然后执行它并关闭它自己,然后复制它自己,以此类推……
我并不要求人们编写我的代码,这可能只是一个有趣的挑战,但我想了解更多关于这方面的东西,并对此表示感谢。
我已经在玩它了,但我不能把我的心绕过去,我已经试着制作一个py文件,然后用它粘贴文件本身的一个副本,这是我能想到的两种不同的方式,但它会永远持续下去。
#i use this piece of code to easily execute the py file using os
os.startfile("file.py")
#and to make new py file i just use open()
file = open("file.py","w")
file.write("""hello world
you can use 3 quote marks to write over multiple lines""")我希望当您运行该程序时,它会复制它自己,运行它,并关闭它自己,然后新运行的程序循环起来。实际上发生的事情是,要么我永远都在写代码,要么,当我将它粘贴在拷贝中的代码嵌入到拷贝文件中时,它正确地说,它不知道代码是什么,因为它正在编写。一切都很混乱,这是很难解释的,很抱歉,现在是午夜自动取款机,我累了。
发布于 2018-12-22 01:23:49
我没有足够的代表回复@Prune:
os.startfile(file)只在Windows上工作,是代之 subprocess.call
shutil.copy2(src, dst)在Windows和Linux上都能工作。
也试试这个解决方案:
import shutil
import subprocess
old_file = __file__
new_file = generate_unique_file_name()
shutil.copy2(old_file, new_file) # works for both Windows and Linux
subprocess.call('python {}'.format(new_file), shell=True)发布于 2018-12-22 00:32:57
你离得很近了,你的事情顺序不对。创建新文件,然后执行它。
import os
old_file = __file__
new_file = generate_unique_file_name()
os.system('cp ' + old_file + ' ' + new_file) #UNIX syntax; for Windows, use "copy"
os.startfile(new_file)您必须选择和编码您喜欢的方法来创建唯一的文件名。您可能需要使用时间戳作为名称的一部分。
您还可能希望在退出之前删除此文件;否则,您最终将使用这些文件填充磁盘。
https://stackoverflow.com/questions/53892106
复制相似问题