有没有办法用python生成fileexception?

2024-04-25 03:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个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""")

我希望当你运行这个程序时,它会复制自己,运行它,然后关闭它,新运行的程序会循环运行。 实际发生的是要么我永远在写代码要么, 当我把它粘贴在自身副本中的代码嵌入到它复制到的副本文件中时, 它正确地说它不知道代码是什么,因为它正在被编写。 这一切真的很混乱,很难解释,我很抱歉 现在是午夜,我累了。你知道吗


Tags: 文件to方法代码py程序pieceos
2条回答

我没有足够的代表回复@Prune:

os.startfile(file)只在Windows上工作,是replaced bysubprocess.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)

你很接近;你把事情安排错了顺序。创建新文件,然后执行它。你知道吗

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)

您必须选择创建唯一文件名的首选方法并对其进行编码。您可能希望使用时间戳作为名称的一部分。你知道吗

您可能还希望在退出之前删除此文件;否则,您最终将用这些文件填充磁盘。你知道吗

相关问题 更多 >