【问题标题】:how to make a python file copy itself then execute the other copy once?如何让python文件复制自己然后执行另一个副本一次?
【发布时间】:2021-06-03 13:12:49
【问题描述】:

我正在使用python进行学校项目,我想知道如何创建一个具有简单这种效果的简单病毒

我试过这个: How do I use shutil to make a python file copy itself after doing a calculation?

还有这个: https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script

然后我不知道如何运行第二个副本

代码示例(我想运行一次)

import os
import shutil

##############

print("hello world")

shutil.copy(__file__, "copy.py") # Copies the file
exec(open("copy.py").read())# Executes the copied file if it is in the same directory as the other file

【问题讨论】:

    标签: python clone virus


    【解决方案1】:

    您可以使用execfile(File Path) 运行第二个文件

    所以你得到了类似的东西

    import os
    import shutil
    import fileinput
    
    ##############
    
    print("hello world")
    
    shutil.copy(__file__, "copy.py") # Copies the file
    
    file = [Path of the copied File]    
    
    for line in fileinput.FileInput(file, inplace=1):
        if "execfile('copy.py')" in line:
            line=line.rstrip()
            line=line.replace(line,"")
        print (line,end="")
    # This could get a problem with large files but should work properly with small files
    
    execfile('copy.py') # Executes the copied file if it is in the same directory as the other file
    # Else give it the directory where the file is stored (with / instead of \)
    

    【讨论】:

    • 你可以更改我的示例代码以了解更多
    • 谢谢你的代码。我刚刚编辑了我的代码以支持 python 3,但我想运行一次副本。当我运行代码时,我得到无限的'''hello world'''然后这个错误代码:(“RecursionError:调用Python对象时超出最大递归深度”)
    • 我认为我的代码现在也应该适用于此
    • 再次编辑,使文件在执行前得到编辑
    【解决方案2】:

    所以我明白了(我也在 reddit 上发过帖子)

    链接:https://www.reddit.com/r/learnpython/cmets/lxupy9/how_to_make_a_python_file_copy_itself_then/

    import shutil
    import subprocess
    import os
    import random
    
    print("hello world")
    new_file_name = str(random.randint(1, 10000)) + ".py"
    shutil.copy(__file__, new_file_name)
    
    subprocess.call((new_file_name), shell=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-14
      • 2023-03-22
      • 2020-10-12
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多