自我复制文件,检索已执行脚本的名称

2024-04-25 17:44:40 发布

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

有没有办法将os.path.basename(__file__)更改为当前正在运行的脚本中执行的文件名?你知道吗

我创建了一个简单的自我复制文件。它从访问根目录开始。然后它对所有可写子目录进行排序,并从列表中随机选择一个。之后,它将写一个.py文件,文件名为随机数字串。然后使用os.path.basename(__file__)检索文件名并将行复制到新编写的文件中。在完成所有这些操作之后,它将执行新创建的文件,该文件将再次重复该过程。但是,在第二轮到中,它保留__file__作为原始文件名,而不是新生成的文件。你知道吗

此部分存储原始目录路径和文件名

import os
import random

orig_dir = os.getcwd()
orig_file = os.path.basename(__file__)

这部分是文件写入过程和新文件的执行。 注意:path变量是根目录中随机选取的子目录,其中包含新写入的文件。

file_create = open(rand_name, "w")
file_create.close()
file_create = open(rand_name, "a")
os.chdir(orig_dir)
copy_file = open(orig_file, "r")
for line in copy_file.readlines():
    file_create.write(line)

file_create.close()
copy_file.close()
os.chdir(path)

exec(open(rand_name).read())

更新: 我把整个剧本贴在下面。我也有一些残忍和丑陋的方法来让它工作,但我更专注于手头的问题。你知道吗

import os
import random

orig_dir = os.getcwd()
orig_file = os.path.basename(__file__)

for loop in range(20):
    os.chdir("..")
root = os.getcwd()

direct = []
for items in os.listdir():
    if os.path.isdir(items) and os.access(items, os.W_OK) and os.access(items, os.R_OK):
        direct.append(items)

path = os.path.join(os.getcwd(), random.choice(direct))
rand_name = str(random.randint(1, 10000000000)) + ".py"
os.chdir(path)
print(path)

# prevents the creation of a duplicate file name in the same location.
# If it is, loops the name generator until a valid name is generated
while True:
    if os.path.isfile(rand_name):
        rand_name = str(random.randint(1, 10000000000)) + ".py"
    else:
        break


file_create = open(rand_name, "w")
file_create.close()
file_create = open(rand_name, "a")
os.chdir(orig_dir)
copy_file = open(orig_file, "r")
for line in copy_file.readlines():
    file_create.write(line)


file_create.close()
copy_file.close()
os.chdir(path)
os.execl(rand_name, ''), 

os.exec(path, '')是我最后尝试的解决方案,但它开始返回PermissionError: [Errno 13] Permission denied。我尝试用sudo权限运行它,但它返回了相同的权限错误。你知道吗


Tags: 文件pathnameincloseos文件名create