Python: невозможно извлечь защищенные паролем данные .rar через мой сценарий python - PullRequest
0 голосов
/ 25 марта 2020

В настоящее время я пытаюсь извлечь данные медицинского изображения из файла .rar, однако у меня возникают проблемы с извлечением данных .rar. Файл защищен паролем, поэтому я ограничен использованием rarfile вместо другой библиотеки извлечения. Я загрузил unrar и убедился, что UNRAR_TOOL указывает на каталог, содержащий unrar.exe. Я включил блок кода ниже, чтобы те, кто читает, сами попробовали код. Сообщение об ошибке, которое я получаю при попытке запустить этот код, можно найти во втором блоке кода. Кроме того, кажется, что это сообщение об ошибке не является сообщением об ошибке, а представляет собой список команд и переключателей, используемых unrar.exe. Любая помощь с этим будет принята с благодарностью!

import numpy as np
import os
from urllib.request import urlretrieve
import rarfile

# Total number of patient data available is 50
total_patients = 1

# Obtaining the data from the URL's
url = []
url_front = 'http://misp.mui.ac.ir/sites/misp.mui.ac.ir/files/attach_files/patient%23'
file_type = '.rar'
password = '545dfds$Dfd46456as'
for patientNum in np.arange(1,total_patients+1):
    url.append(url_front + str(patientNum) + file_type)
    file_name = os.path.basename(url[patientNum-1])
    full_file = os.path.join(os.getcwd(),'Datasets',file_name)

    # Downloads file only if it doesn't exist already
    if not os.path.isfile(full_file):
        urlretrieve(url[patientNum-1],full_file)

    rf = rarfile.RarFile(full_file)
    rf.setpassword(password)
    rf.extractall()
RarUserError: User error [7]:
UNRAR 5.80 x86 freeware      Copyright (c) 1993-2019 Alexander Roshal

Usage:     unrar <command> -<switch 1> -<switch N> <archive> <files...>
               <@listfiles...> <path_to_extract\>

<Commands>
  e             Extract files without archived paths
  l[t[a],b]     List archive contents [technical[all], bare]
  p             Print file to stdout
  t             Test archive files
  v[t[a],b]     Verbosely list archive contents [technical[all],bare]
  x             Extract files with full path

<Switches>
  -             Stop switches scanning
  @[+]          Disable [enable] file lists
  ac            Clear Archive attribute after compression or extraction
  ad            Append archive name to destination path
  ag[format]    Generate archive name using the current date
  ai            Ignore file attributes
  ap<path>      Set path inside archive
  c-            Disable comments show
  cfg-          Disable read configuration
  cl            Convert names to lower case
  cu            Convert names to upper case
  dh            Open shared files
  ep            Exclude paths from names
  ep3           Expand paths to full including the drive letter
  f             Freshen files
  id[c,d,p,q]   Disable messages
  ierr          Send all messages to stderr
  inul          Disable all messages
  ioff[n]       Turn PC off after completing an operation
  kb            Keep broken extracted files
  n<file>       Additionally filter included files
  n@            Read additional filter masks from stdin
  n@<list>      Read additional filter masks from list file
  o[+|-]        Set the overwrite mode
  oc            Set NTFS Compressed attribute
  ol[a]         Process symbolic links as the link [absolute paths]
  or            Rename files automatically
  ow            Save or restore file owner and group
  p[password]   Set password
  p-            Do not query password
  r             Recurse subdirectories
  ri<P>[:<S>]   Set priority (0-default,1-min..15-max) and sleep time in ms
  sc<chr>[obj]  Specify the character set
  sl<size>      Process files with size less than specified
  sm<size>      Process files with size more than specified
  ta[mcao]<d>   Process files modified after <d> YYYYMMDDHHMMSS date
  tb[mcao]<d>   Process files modified before <d> YYYYMMDDHHMMSS date
  tn[mcao]<t>   Process files newer than <t> time
  to[mcao]<t>   Process files older than <t> time
  ts[m,c,a,p]   Save or restore time (modification, creation, access, preserve)
  u             Update files
  v             List all volumes
  ver[n]        File version control
  vp            Pause before each volume
  x<file>       Exclude specified file
  x@            Read file names to exclude from stdin
  x@<list>      Exclude files listed in specified list file
  y             Assume Yes on all queries
...