Fehler beim Extrahieren des Archivs: [Errno 2] Keine solche Datei oder kein solches Verzeichnis: 'update.rar'
Beim Aktualisieren des Programms ist ein Fehler aufgetreten: [WinError 2] Die angegebene Datei kann nicht gefunden werden: „update.rar“
update.py
Code: Select all
import requests
import zipfile
import os
import sys
import shutil
import rarfile
def download_update(url, filename):
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(filename, 'wb') as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
except Exception as e:
print(f"Ошибка при загрузке файла: {e}")
def extract_archive(filename, extract_to):
try:
if filename.endswith('.zip'):
with zipfile.ZipFile(filename, 'r') as zip_ref:
zip_ref.extractall(extract_to)
elif filename.endswith('.rar'):
with rarfile.RarFile(filename, 'r') as rar_ref:
rar_ref.extractall(extract_to)
else:
print(f"Неизвестный формат архива: {filename}")
except Exception as e:
print(f"Ошибка при извлечении архива: {e}")
def update_program(repo_url, version):
try:
archive_url = f"https://github.com/{repo_url}/releases/download/{version}/uto-farm-{version}.rar"
archive_filename = "update.rar"
download_update(archive_url, archive_filename)
if not os.path.exists("update_dir"):
os.makedirs("update_dir")
extract_archive(archive_filename, "update_dir")
# Копирование файлов из распакованного архива в текущую директорию
for item in os.listdir("update_dir"):
s = os.path.join("update_dir", item)
d = os.path.join(".", item)
if os.path.isdir(s):
shutil.copytree(s, d, dirs_exist_ok=True)
else:
shutil.copy2(s, d)
# Удаление временной директории и архива
shutil.rmtree("update_dir")
os.remove(archive_filename)
print("Программа успешно обновлена.")
os.execv(sys.executable, [sys.executable] + sys.argv)
except Exception as e:
print(f"Произошла ошибка при обновлении программы: {e}")
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage: update.py ")
sys.exit(1)
update_program(sys.argv[1], sys.argv[2])
Code: Select all
def check_for_updates():
try:
response = requests.get(LATEST_RELEASE_URL, headers=headers)
response.raise_for_status()
latest_release = response.json()
latest_version = latest_release['tag_name']
if latest_version > CURRENT_VERSION:
repo_url = "Waywardfucker/uto-farm"
subprocess.run(['update.exe', repo_url, latest_version])
sys.exit(0)
else:
print("У вас установлена последняя версия.")
except Exception as e:
print(f"Не удалось проверить наличие обновлений. Произошла ошибка: {e}")
Ich berücksichtige, dass ich Releases möglicherweise falsch erstelle. Oder etwas anderes, auf jeden Fall komme ich selbst nicht dahinter.
Geben Sie hier die Bildbeschreibung ein
Geben Sie hier die Bildbeschreibung ein
Früher habe ich versucht, nur mit .exe zu arbeiten, aber dort Es trat derselbe Fehler auf und ich beschloss, andere Optionen auszuprobieren.
Geben Sie hier die Bildbeschreibung ein
Ich habe versucht, den Code auf jede erdenkliche Weise zu ändern, aber jedes Mal gab es andere Probleme. Ein Problem war unter anderem die Neigung des Bildschirms. Hier ist das Endergebnis, zu dem ich gekommen bin. Ich bin ehrlich gesagt verwirrt, aber das ist nicht der Punkt, alles führt zu Fehlern.
Code: Select all
import requests
import zipfile
import os
import sys
import shutil
import rarfile
def download_update(url, filename):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers, stream=True)
response.raise_for_status()
with open(filename, 'wb') as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
print(f"Файл {filename} успешно загружен.")
except Exception as e:
print(f"Ошибка при загрузке файла: {e}")
def extract_archive(filename, extract_to):
try:
if filename.endswith('.zip'):
with zipfile.ZipFile(filename, 'r') as zip_ref:
zip_ref.extractall(extract_to)
elif filename.endswith('.rar'):
with rarfile.RarFile(filename, 'r') as rar_ref:
rar_ref.extractall(extract_to)
else:
print(f"Неизвестный формат архива: {filename}")
print(f"Архив {filename} успешно распакован в {extract_to}.")
except Exception as e:
print(f"Ошибка при распаковке архива: {e}")
def update_program(repo_url, version):
try:
archive_url = f"https://github.com/{repo_url}/releases/download/{version}/uto-farm-{version}.rar"
print(f"Загрузка архива с URL: {archive_url}")
archive_filename = "update.rar"
download_update(archive_url, archive_filename)
extract_archive(archive_filename, "update_dir")
# Копирование файлов из распакованного архива в текущую директорию
for item in os.listdir("update_dir"):
s = os.path.join("update_dir", item)
d = os.path.join(".", item)
if os.path.isdir(s):
shutil.copytree(s, d, dirs_exist_ok=True)
else:
shutil.copy2(s, d)
print("Файлы успешно скопированы.")
# Удаление временной директории и архива
shutil.rmtree("update_dir")
os.remove(archive_filename)
# Удаление текущей программы
current_script = sys.argv[0]
os.chmod(current_script, 0o777) # Установка прав доступа
os.remove(current_script)
print("Программа успешно обновлена и текущий скрипт удален.")
os.execv(sys.executable, [sys.executable] + sys.argv)
except Exception as e:
print(f"Произошла ошибка при обновлении программы: {e}")
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage: update.py ")
sys.exit(1)
update_program(sys.argv[1], sys.argv[2])