code cleanup

pull/155/head
Alin Trăistaru 7 years ago
parent 2691bab31f
commit 2a21a37ab4

@ -1,5 +1,4 @@
import os
import platform
import inspect
from . import config
@ -8,8 +7,8 @@ try:
except:
try:
from .colorama import init as colorama_init, Fore, Back, Style
except:
pass
except Exception as e:
raise e
finally:
try:
colorama_init(autoreset=True)
@ -38,7 +37,8 @@ def fnCall():
Prints filename:line:function for parent and grandparent.
"""
if not config.debug: return
if not config.debug:
return
print(colors.OKGREEN + colors.BOLD + "=== DEBUG === | %s:%d:%s() called from %s:%d:%s()" % (
inspect.stack()[1][1].split(os.sep)[-1],
@ -48,4 +48,3 @@ def fnCall():
inspect.stack()[2][2],
inspect.stack()[2][3],
)+colors.RESET)

@ -7,7 +7,6 @@
# under the terms of GNU General Public License, v.2 or above
import os
import string
import platform
import re
from .iso import *
@ -143,15 +142,13 @@ def distro(iso_cfg_ext_dir, iso_link):
if distro:
return distro
# FIXME: See the below comments.
'''
else:
# FIXME: The idea of detecting as generic is to work like a unetbootin if other methods fails.
# This simply extracts distro to root of the USB and install syslinux on isolinux.bin directory.
# All works fine but unable to boot the distro successfully. Also, see the generic section from
# syslinux, update_cfg and install_distro modules.
if self.isolinux_bin_exist():
return "generic"
'''
# else:
# # FIXME: The idea of detecting as generic is to work like a unetbootin if other methods fails.
# # This simply extracts distro to root of the USB and install syslinux on isolinux.bin directory.
# # All works fine but unable to boot the distro successfully. Also, see the generic section from
# # syslinux, update_cfg and install_distro modules.
# if self.isolinux_bin_exist():
# return "generic"
else:
return None

@ -243,17 +243,17 @@ def read_input_yes():
return False
def strings(filename, min=4):
def strings(filename, _min=4):
with open(filename, errors="ignore") as f:
result = ""
for c in f.read():
if c in string.printable:
result += c
continue
if len(result) >= min:
if len(result) >= _min:
yield result
result = ""
if len(result) >= min: # catch result at EOF
if len(result) >= _min: # catch result at EOF
yield result

@ -147,19 +147,16 @@ def grub_custom_menu(mbus_grub_cfg_path, distro):
if distro in ['sgrubd2', 'raw_iso']:
grub_raw_iso(mbus_grub_cfg_path)
'''
with open(mbus_grub_cfg_path, 'a') as f:
f.write("#start " + iso.iso_basename(config.image_path) + "\n")
f.write(grub_raw_iso())
f.write("#end " + iso.iso_basename(config.image_path) + "\n")
elif iso_size_mb < 750.0:
grub_raw_iso(mbus_grub_cfg_path)
'''
# with open(mbus_grub_cfg_path, 'a') as f:
# f.write("#start " + iso.iso_basename(config.image_path) + "\n")
# f.write(grub_raw_iso())
# f.write("#end " + iso.iso_basename(config.image_path) + "\n")
#
#
# elif iso_size_mb < 750.0:
# grub_raw_iso(mbus_grub_cfg_path)
else:
return False
@ -308,7 +305,7 @@ def iso2grub2(iso_dir):
for _lines in kernel_text:
kernel_line = extract_kernel_line(_lines[0][1], _lines[0][0],
iso_bin_dir)
if kernel_line is '':
if kernel_line == '':
continue
else:
break
@ -322,7 +319,7 @@ def iso2grub2(iso_dir):
for _lines in initrd_text:
initrd_line = extract_kernel_line(_lines[0][1], _lines[0][0],
iso_bin_dir)
if initrd_line is '':
if initrd_line == '':
continue
else:
break

@ -12,9 +12,7 @@ import subprocess
import collections
import platform
import signal
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from .gui.ui_multibootusb import Ui_MainWindow
from .gen import *
from . import iso
@ -28,15 +26,14 @@ if platform.system() == "Windows":
def dd_linux():
import time
input = "if=" + config.image_path
_input = "if=" + config.image_path
in_file_size = float(os.path.getsize(config.image_path))
output = "of=" + config.usb_disk
_output = "of=" + config.usb_disk
os.system("umount " + config.usb_disk + "1")
command = ['dd', input, output, "bs=1M", "oflag=sync"]
command = ['dd', _input, _output, "bs=1M", "oflag=sync"]
log("Executing ==> " + " ".join(command))
dd_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
# bar = progressbar.ProgressBar(redirect_stdout=True)
pbar = progressbar.ProgressBar(
maxval=100,
widgets=[
@ -73,10 +70,10 @@ def dd_win():
windd = resource_path(os.path.join("data", "tools", "dd", "dd.exe"))
if os.path.exists(resource_path(os.path.join("data", "tools", "dd", "dd.exe"))):
log("dd exist")
input = "if=" + config.image_path
_input = "if=" + config.image_path
in_file_size = float(os.path.getsize(config.image_path) / 1024 / 1024)
output = "of=\\\.\\" + config.usb_disk
command = [windd, input, output, "bs=1M", "--progress"]
_output = "of=\\\.\\" + config.usb_disk
command = [windd, _input, _output, "bs=1M", "--progress"]
log("Executing ==> " + " ".join(command))
dd_process = subprocess.Popen(command, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
shell=False)
@ -127,19 +124,8 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
self.ui.imager_iso_size.setText("ISO Size: " + self.iso_size + " MB")
log("ISO Size is " + self.iso_size + " MB")
# def onImagerComboChange(self):
# config.imager_usb_disk = str(self.ui.comboBox_2.currentText())
# if bool(config.imager_usb_disk):
# self.ui.imager_disk_label.setText(self.imager_usb_detail(config.imager_usb_disk, partition=0).usb_type)
# self.ui.imager_total_size.setText(usb.bytes2human(int(self.imager_usb_detail(config.imager_usb_disk, partition=0).total_size)))
#
# if platform.system() == "Linux":
# self.ui.label_imager_uuid.setText("Disk Model:")
# self.ui.imager_uuid.setText(str(self.imager_usb_detail(config.imager_usb_disk, partition=0).model))
# else:
# self.ui.imager_uuid.setText(self.imager_usb_detail(config.imager_usb_disk, partition=0).model)
def imager_list_usb(self, partition=1):
@staticmethod
def imager_list_usb(partition=1):
"""
Function to detect whole USB disk. It uses lsblk package on Linux.
:param partition: What to return. By default partition is set.
@ -148,7 +134,7 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
disk = []
if platform.system() == "Linux":
output = subprocess.check_output("lsblk -i", shell=True)
if not partition == 1:
if partition != 1:
for line in output.splitlines():
line = line.split()
if (line[2].strip()) == b'1' and (line[5].strip()) == b'disk':
@ -159,7 +145,6 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
if (line[2].strip()) == b'1' and line[5].strip() == b'part':
disk.append(str("/dev/" + str(line[0].strip()[2:])))
else:
if partition == 1 or not partition == 1:
oFS = win32com.client.Dispatch("Scripting.FileSystemObject")
oDrives = oFS.Drives
for drive in oDrives:
@ -167,7 +152,8 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
disk.append(drive)
return disk
def imager_usb_detail(self, usb_disk, partition=1):
@staticmethod
def imager_usb_detail(usb_disk, partition=1):
"""
Function to detect details of USB disk using lsblk
:param usb_disk: path to usb disk
@ -180,7 +166,7 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
output = subprocess.check_output("lsblk -ib " + usb_disk, shell=True)
for line in output.splitlines():
line = line.split()
if not partition == 1:
if partition != 1:
if line[2].strip() == b'1' and line[5].strip() == b'disk':
total_size = line[3]
if not total_size:

@ -10,7 +10,6 @@
import sys
import os
import string
import platform
import re
from .gen import *
from .isodump3 import ISO9660
@ -56,11 +55,7 @@ def isolinux_bin_exist(iso_link):
"""
if os.path.exists(iso_link):
iso_file_list = _7zip.list_iso(iso_link)
if any("isolinux.bin" in s.lower() for s in iso_file_list):
return True
else:
return False
return bool(any("isolinux.bin" in s.lower() for s in iso_file_list))
def iso_size(iso_link):
@ -74,10 +69,7 @@ def is_bootable(iso_link):
"""
iso9660fs = ISO9660(iso_link)
isBootable = iso9660fs.checkISOBootable()
if isBootable:
return True
else:
return False
return bool(isBootable)
def isolinux_bin_dir(iso_link):
@ -162,14 +154,14 @@ def isolinux_version(isolinux_bin_path):
return str(number)
def iso_extract_file(iso_link, dest_dir, filter):
def iso_extract_file(iso_link, dest_dir, _filter):
"""
Extract the specific file(s) from an ISO
:param dest_dir: Path to destination directory.
:param filter: Filter to extract particular file(s)
:return: Extract file(s) to destination.
"""
_7zip.extract_iso(iso_link, dest_dir, filter)
_7zip.extract_iso(iso_link, dest_dir, _filter)
def extract_cfg_file(iso_link):
@ -232,4 +224,3 @@ if __name__ == '__main__':
iso_extract_full(iso_path, 'test')
iso_extract_file(iso_path, 'test', 'isolinux.bin')
log(isolinux_version(test_iso_bin_path))

@ -6,7 +6,6 @@
# Licence: This file is a part of multibootusb package. You can redistribute it or modify
# under the terms of GNU General Public License, v.2 or above
import sys
import os
import platform
import tarfile
@ -92,7 +91,7 @@ def create_persistence():
if subprocess.call(persistence_dd_cmd, shell=True) == 0:
gen.log("\nSuccessfully created persistence file...\n")
if not config.distro == 'fedora':
if config.distro != 'fedora':
gen.log('Applying filesystem to persistence file...')
config.status_text = 'Applying filesystem to persistence file. Please wait...'
gen.log('Executing ==> ' + persistence_mkfs_cmd)
@ -111,4 +110,3 @@ def extract_file(file_path, install_dir):
tar = tarfile.open(file_path, "r:bz2")
tar.extractall(install_dir)
tar.close()

@ -11,7 +11,6 @@
import os
import subprocess
import platform
from .admin import adminCmd
from PyQt5 import QtWidgets
from .gui.ui_multibootusb import Ui_MainWindow
from .gen import *
@ -102,9 +101,7 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
cmd = qemu + ' -hda ' + qemu_usb_disk + ram + ' -vga std'
try:
log('Executing ==> ' + cmd)
# adminCmd([qemu, '-hda', usb_disk[:-1], '-m', ram, '-vga std'], gui=True)
subprocess.Popen(cmd, shell=True)
# adminCmd(qemu_cmd, gui=True)
except:
QtWidgets.QMessageBox.information(self, 'Error...', 'Error booting USB\n\nUnable to start QEMU.')
@ -134,7 +131,8 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
else:
return selected_ram
def check_qemu_exist(self):
@staticmethod
def check_qemu_exist():
"""
Check if QEMU is available on host system.
:return: path to QEMU program or None otherwise.
@ -158,24 +156,21 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
return qemu
def get_physical_disk_number(self, usb_disk):
@staticmethod
def get_physical_disk_number(usb_disk):
"""
Get the physical disk number as detected ny Windows.
:param usb_disk: USB disk (Like F:)
:return: Disk number.
"""
import wmi
c = wmi.WMI ()
for physical_disk in c.Win32_DiskDrive ():
for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"):
c = wmi.WMI()
for physical_disk in c.Win32_DiskDrive():
for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
if logical_disk.Caption == usb_disk:
"""
log physical_disk.Caption
log partition.Caption
log logical_disk.Caption
"""
# log physical_disk.Caption
# log partition.Caption
# log logical_disk.Caption
log("Physical Device Number is " + partition.Caption[6:-14])
return str(partition.Caption[6:-14])

@ -7,7 +7,6 @@
# under the terms of GNU General Public License, v.2 or above
import os
import sys
import subprocess
import platform
from .gen import *
@ -39,7 +38,7 @@ def set_boot_flag(usb_disk):
return False
def syslinux_default(usb_disk, version=4):
def syslinux_default(usb_disk):
"""
Install Syslinux of a selected drive
:param usb_disk: '/dev/sdx' on linux and 'E:' on Windows
@ -152,7 +151,7 @@ def syslinux_distro_dir(usb_disk, iso_link, distro):
if platform.system() == "Linux":
syslinux_path = os.path.join(multibootusb_host_dir(), "syslinux", "bin", "syslinux") + config.syslinux_version
if os.access(syslinux_path, os.X_OK) is False:
subprocess.call('chmod +x ' + syslinux_path, shell=True) == 0
subprocess.call('chmod +x ' + syslinux_path, shell=True)
sys_cmd = syslinux_path + option + quote(distro_syslinux_install_dir) + ' ' + usb_disk
dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1'
log("Executing ==> " + sys_cmd)
@ -194,7 +193,7 @@ def syslinux_distro_dir(usb_disk, iso_link, distro):
ext_cmd = syslinux_path + " --install " + distro_syslinux_install_dir
dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1'
if os.access(syslinux_path, os.X_OK) is False:
subprocess.call('chmod +x ' + syslinux_path, shell=True) == 0
subprocess.call('chmod +x ' + syslinux_path, shell=True)
log("Executing ==> " + ext_cmd)
if subprocess.call(ext_cmd, shell=True) == 0:
log("\nSyslinux install on distro directory is successful...\n")

@ -11,7 +11,8 @@ __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
# from __future__ import print_function
import os, re
import os
import re
def node_mountpoint(node):
@ -133,16 +134,6 @@ class UDisks2(object):
def mount(self, device_node_path):
d = self.device(device_node_path)
# euid = os.environ['SUDO_UID']
# egid = os.environ['SUDO_GID']
#
# if euid and egid:
# user, group = int(euid), int(egid)
# else:
# user, group = os.getuid(), os.getgid()
#
# mount_options = ['rw', 'noexec', 'nosuid', 'nodev', 'uid=%d' % user, 'gid=%d' % group]
mount_options = ['rw', 'noexec', 'nosuid', 'nodev']
try:
@ -158,7 +149,7 @@ class UDisks2(object):
mp = node_mountpoint(str(device_node_path))
if mp is None:
raise
finally:
return mp
def unmount(self, device_node_path):

@ -84,7 +84,7 @@ def disk_usage(mount_path):
raise NotImplementedError("Platform not supported.")
def list_devices(partition=1, fixed=False):
def list_devices(fixed=False):
"""
List inserted USB devices.
:return: USB devices as list.
@ -97,7 +97,7 @@ def list_devices(partition=1, fixed=False):
try:
import pyudev
except Exception as e:
gen.log('Pydev is not installed on host system. Using the inbuilt one.')
gen.log('PyUdev is not installed on host system, using built-in.')
from . import pyudev
context = pyudev.Context()
@ -209,12 +209,9 @@ def details_udev(usb_disk_part):
import pyudev
except:
from . import pyudev
"""
Try with PyUdev to get the details of USB disks.
This is the easiest and reliable method to find USB details.
Also, it is a standalone package and no dependencies are required.
"""
# gen.log "Using PyUdev for detecting USB details..."
# Try with PyUdev to get the details of USB disks.
# This is the easiest and reliable method to find USB details.
# Also, it is a standalone package and no dependencies are required.
context = pyudev.Context()
try:
device = pyudev.Device.from_device_file(context, usb_disk_part)
@ -367,18 +364,17 @@ def win_disk_details(disk_drive):
size_total = shutil.disk_usage(mount_point)[0]
size_used = shutil.disk_usage(mount_point)[1]
size_free = shutil.disk_usage(mount_point)[2]
'''
# The below code works only from vista and above. I have removed it as many people reported that the software
# was not working under windows xp. Even then, it is significantly slow if 'All Drives' option is checked.
# Removing the code doesn't affect the functionality as it is only used to find vendor id and model of the drive.
c = wmi.WMI()
for physical_disk in c.Win32_DiskDrive(InterfaceType="USB"):
for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
if logical_disk.Caption == disk_drive:
vendor = (physical_disk.PNPDeviceID.split('&VEN_'))[1].split('&PROD_')[0]
model = (physical_disk.PNPDeviceID.split('&PROD_'))[1].split('&REV_')[0]
'''
# c = wmi.WMI()
# for physical_disk in c.Win32_DiskDrive(InterfaceType="USB"):
# for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
# for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
# if logical_disk.Caption == disk_drive:
# vendor = (physical_disk.PNPDeviceID.split('&VEN_'))[1].split('&PROD_')[0]
# model = (physical_disk.PNPDeviceID.split('&PROD_'))[1].split('&REV_')[0]
return {'uuid': uuid, 'file_system': file_system, 'label': label, 'mount_point': mount_point,
'size_total': size_total, 'size_used': size_used, 'size_free': size_free,

Loading…
Cancel
Save