有没有办法用 python 进行文件接收?
is there a way of making a file-ception with 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""")
我希望当你 运行 程序时,它会复制自己,运行 s 它,然后关闭自己,然后新的 运行 程序循环。
实际发生的是,要么我永远在写代码,要么,
当我嵌入代码时,它会将自己的副本粘贴到它复制到副本文件的内容中,
它正确地说它不知道该代码是什么,因为它正在编写。
这一切真的很混乱,这很难解释,我很抱歉
现在是半夜自动取款机,我累了。
你很接近;你的东西顺序错了。创建新文件,然后执行它。
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)
您必须选择并编写您喜欢的创建唯一文件名的方法。您可能希望使用时间戳作为名称的一部分。
您可能还想在退出前删除该文件;否则,您最终会用这些文件填满您的磁盘。
我没有足够的代表回复@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)
我想制作一个 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""")
我希望当你 运行 程序时,它会复制自己,运行 s 它,然后关闭自己,然后新的 运行 程序循环。 实际发生的是,要么我永远在写代码,要么, 当我嵌入代码时,它会将自己的副本粘贴到它复制到副本文件的内容中, 它正确地说它不知道该代码是什么,因为它正在编写。 这一切真的很混乱,这很难解释,我很抱歉 现在是半夜自动取款机,我累了。
你很接近;你的东西顺序错了。创建新文件,然后执行它。
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)
您必须选择并编写您喜欢的创建唯一文件名的方法。您可能希望使用时间戳作为名称的一部分。
您可能还想在退出前删除该文件;否则,您最终会用这些文件填满您的磁盘。
我没有足够的代表回复@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)