有没有办法用python进行文件接收?

时间:2018-12-22 00:21:07

标签: python filesystems

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

我希望当您运行该程序时,它会复制自己,运行并关闭自己,并且新运行的程序会循环运行。 实际发生的事情是我永远在写代码,或者 当我嵌入代码时,它将其自身的副本粘贴到要复制到副本文件中的代码中, 它正确地说它不知道该代码是什么,因为它正在被编写。 这真的很令人困惑,这很难解释,对不起 这是午夜的大气压,我很累。

2 个答案:

答案 0 :(得分:1)

我没有足够的回复来回复@Prune:

os.startfile(file)仅在Windows上有效,并且是replaced by 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)

答案 1 :(得分:0)

您接近了;您的订单顺序错误。创建新文件,然后然后执行。

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)

您将必须选择和编码用于创建唯一文件名的首选方法。您可能要使用时间戳作为名称的一部分。

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