def delete_last_lines(n): if 'LINUX' in platform_system().upper(): for _ in range(n): sys_stdout.write(LINUX_CURSOR_UP_ONE) sys_stdout.write(LINUX_ERASE_LINE) elif 'WINDOWS' in platform_system().upper(): os_system('cls')
def setDirectory(self): self.directory = resolveFilename(SCOPE_DEFAULTPARTITIONMOUNTDIR) self.xmlfile = "defaultwizard.xml" if self.directory: os_system( "mount %s %s" % (resolveFilename(SCOPE_DEFAULTPARTITION), self.directory))
def removeConf(self, extra_args): printDebugMsg("removeConf") if fileExists("/etc/hostapd.conf", 0): os_system("mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back") fp = file("/etc/network/interfaces", 'w') fp.write( "# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n" ) fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") if apModeConfig.usedhcp.value is True: fp.write("iface eth0 inet dhcp\n") else: fp.write("iface eth0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value)) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value)) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value)) fp.close() self.setIpForward(0) self.networkRestart_start()
def removeCmdOnclose(self, reval): self.container.appClosed.remove(self.removeCmdOnclose) self.container.dataAvail.remove(self.cmdData) if self.errormessage == '': self.count_removed = self.count_removed + 1 if not os_path.exists('/tmp/.restart_e2') and not self.currentpkgname.startswith('enigma2-skin-'): cmd = 'touch /tmp/.restart_e2' os_system(cmd) else: self.errormessage = '' self.count_failed_remove = self.count_failed_remove + 1 self.currentIndex = self.currentIndex + 1 if self.currentIndex < len(self.removeList): pkgname = str(os_path.basename(self.removeList[self.currentIndex])) self.currentpkgname = pkgname.split('_')[0] self['package'].setText(self.currentpkgname) self.setTitle(_('Removing') + '...') self['status'].setText(_('Removing from root...')) self.removeIpk() else: if not len(self.installList) == 0: self.setTitle(_('Install') + ' & ' + _('Remove')) else: self.setTitle(_('Remove')) self['package'].setText(_('Terminate')) self['status'].setText(_('%d package(s) installed, %d package(s) removed, %d package(s) failed,\n press ok to see log or cancel to exit.') % (self.count_success, self.count_removed, self.count_failed_remove + self.count_failed_install))
def checkStoragePath(self): tmppath = config.mediaportal.storagepath.value if tmppath != "/tmp" and tmppath != "/media/ba": if os_path.islink(tmppath): tmppath = os_readlink(tmppath) loopcount = 0 while not os_path.ismount(tmppath): loopcount += 1 tmppath = os_path.dirname(tmppath) if tmppath == "/" or tmppath == "" or loopcount > 50: self.session.open( MessageBox, _("Error: Can not create cache-folders inside flash memory. Check your Cache-Folder Settings!" ), type=MessageBox.TYPE_INFO, timeout=20) return False os_system("mkdir -p " + config.mediaportal.storagepath.value) if not os_path.exists(config.mediaportal.storagepath.value): self.session.open( MessageBox, _("Error: No write permission to create cache-folders. Check your Cache-Folder Settings!" ), type=MessageBox.TYPE_INFO, timeout=20) return False else: return True
def test(self): prevOK = self.testOK link = "down" for iface in self.get_iface_list(): if "lo" in iface: continue if os_path.exists("/sys/class/net/%s/operstate" % (iface)): fd = open("/sys/class/net/%s/operstate" % (iface), "r") link = fd.read().strip() fd.close() if link != "down": break if link != "down": s = socket(AF_INET, SOCK_STREAM) s.settimeout(self.testTime) try: self.testOK = not bool( s.connect_ex((self.testHost, self.testPort))) except: self.testOK = False s.close() else: self.testOK = False if prevOK != self.testOK: self.downstream_elements.changed((self.CHANGED_POLL, )) if prevOK and self.failCmd: os_system('/bin/sh -c "%s" &' % (self.failCmd))
def render(self, request): self.request = request graboptions = "" if "format" in request.args.keys(): self.fileformat = request.args["format"][0] else: self.fileformat = "jpg" if self.fileformat == "jpg": graboptions += " -j 100" elif self.fileformat == "png": graboptions += " -p" if "r" in request.args.keys(): size = request.args["r"][0] graboptions += " -r %s" % size if "mode" in request.args.keys(): mode = request.args["mode"][0] if mode == "osd": graboptions += " -o" elif mode == "video": graboptions += " -v" self.filepath = "/tmp/screenshot." + self.fileformat grabcommand = GRAB_PATH + graboptions + " " + self.filepath #self.container.execute(grabcommand) os_system(grabcommand) self.grabFinished()
def pepstats(file, outdir): outfile = os_path.join(outdir, "results.pepstats") args = ("pepstats -sequence {0} -outfile ".format(file) + outfile) os_system(args) f = open(outfile, "r") hydrop = {} weight = {} isoelec = {} polar = {} for line in f: if "PEPSTATS of" in line: splitdata = line.split() seq = splitdata[2].split('_')[0] elif "Molecular weight = " in line: splitdata = line.split() w = splitdata[3] weight[seq] = w elif "Isoelectric Point = " in line: splitdata = line.split() i = splitdata[3] isoelec[seq] = i elif "Polar " in line: splitdata = line.split() percent = splitdata[3] polar[seq] = percent seq return (hydrop, weight, isoelec, polar)
def garnier(file, outdir): fixfile = file + '.fix.fasta' noAmbiguousSeqs(file, fixfile) outfile = os_path.join(outdir, "garnier.txt") args = ("garnier -sequence {0} -outfile ".format(fixfile) + outfile) os_system(args) f = open(outfile, "r") helices = {} sheets = {} turns = {} coils = {} for line in f: if "Sequence:" in line: splitdata = line.split() seq = splitdata[2].split('_')[0] elif "percent:" in line: percents = line.split() h = percents[3] e = percents[5] t = percents[7] c = percents[9] helices[seq] = h sheets[seq] = e turns[seq] = t coils[seq] = c return (helices, sheets, turns, coils)
def runMenu(self, menuName = "Menu", MenuFolder = "" ): os_system( "%s/_MenuGenerator.sh %s" % (MenuFolder, MenuFolder) ) if pathExists("%s/_MenuItems" % MenuFolder ) is True: from GOSmenu import myMenu self.session.openWithCallback(self.prepareListForSelector(), myMenu, MenuFolder = MenuFolder) else: self.session.openWithCallback(self.prepareListForSelector, MessageBox,_("No config file for %s","plugin-GOSmanager") % menuName, type = MessageBox.TYPE_INFO)
def save(self): plugin = self["list"].l.getCurrentSelection()[0] plugin.icon = None if not fileExists( "/usr/lib/enigma2/python/Plugins/Extensions/EasyMedia/" + plugin.name + ".plug"): try: outf = open( ("/usr/lib/enigma2/python/Plugins/Extensions/EasyMedia/" + plugin.name + ".plug"), 'wb') pickle.dump(plugin, outf) outf.close() self.session.open(MessageBox, text=(plugin.name + _(" added to EasyMedia")), type=MessageBox.TYPE_INFO) except: self.session.open(MessageBox, text="Write Error!", type=MessageBox.TYPE_WARNING) else: order = 'rm -f \"' + '/usr/lib/enigma2/python/Plugins/Extensions/EasyMedia/' + plugin.name + '.plug' + '\"' try: os_system(order) self.session.open(MessageBox, text=(plugin.name + _(" removed from EasyMedia")), type=MessageBox.TYPE_INFO) except: self.session.open(MessageBox, text="Write Error!", type=MessageBox.TYPE_WARNING)
def save(self): plugin = self["pluginlist"].getCurrent()[0] print(plugin) if not fileExists(PluginsDir + 'EasyMedia/' + plugin.name + '.plug'): try: outf = open( (PluginsDir + 'EasyMedia/' + plugin.name + '.plug'), 'wb') dump(plugin, outf) outf.close() self.session.open(MessageBox, text=(plugin.name + _(" added to EasyMedia")), type=MessageBox.TYPE_INFO) except: self.session.open(MessageBox, text="Write Error!", type=MessageBox.TYPE_WARNING) else: order = 'rm -f \"' + PluginsDir + 'EasyMedia/' + plugin.name + '.plug' + '\"' try: os_system(order) self.session.open(MessageBox, text=(plugin.name + _(" removed from EasyMedia")), type=MessageBox.TYPE_INFO) except: self.session.open(MessageBox, text="Write Error!", type=MessageBox.TYPE_WARNING)
def take_screenshot(filename): # A few words about the fastest way to take a screenshot with Python. # Initially the Pillow library was used, in particular PIL.ImageGrab(), # which is compatible only with Windows and macOS (press f for Linux). # However, after some tests (on my machine specifically), it takes on average # a second to capture and save a screenshot to disk, which is too much # considering the ten seconds available to answer the question. #from PIL import ImageGrab #ImageGrab.grab().save("screen.png") #real 0m1.077s # So I tried the MSS library, which can halve the time required # to take and save a screenshot to disk. Plus, it's cross-platform. #from mss import mss #with mss() as sct: # sct.shot() # saved as "monitor-1.png" by default #real 0m0.465s # But the choice fell on the macOS system utility, screencapture (rip cross-platform), # which manages to do the same operation in less than a quarter of a second. #from os import system #system("screencapture screen.png") # use -R to specify a region #real 0m0.206s # Take a screenshot of the emulator window os_system(f"screencapture -R {Coords.emulator.to_string()} {filename}") # Returns the screenshot already converted to grayscale return load_image(filename)
def addSkinToBackupDirs(self): from os import system as os_system, path as os_path # if not default skin if os_system( "grep config.skin.primary_skin /etc/enigma2/settings 1>/dev/null" ) == 0 and config.skin.primary_skin.value != "skin.xml": skinName = config.skin.primary_skin.value[:-9] skinDir = "/usr/share/enigma2/%s" % skinName skinFiles = skinDir + "/.skin_files" if os_path.exists(skinFiles): print "maybe skin from backup, not from opkg" else: if os_system("grep %s /usr/lib/opkg/info/*.list 1>/dev/null" % skinName) == 0: os_system( "opkg files `opkg search %s | awk '{print $1}'` > %s" % ("/usr/share/enigma2/" + config.skin.primary_skin.value, skinFiles)) self.backupdirs = self.backupdirs + " " + skinFiles else: print "skin is not from backup and not from opkg, can not know skin files" return self.backupdirs = self.backupdirs + " " + skinDir for line in open(skinFiles).readlines(): if os_path.exists( line.split("\n")[0]) and not line.startswith(skinDir): self.backupdirs = self.backupdirs + " " + line.split( "\n")[0]
def remove_ca(request, cert_id): """ Function called when a Trusted CA certificate is deleted. It will erase-it on disk. :param request: Django request object :param cert_id: String id of certificate to erase :return: """ try: certificate = SSLCertificate(ObjectId(cert_id)) except Exception as e: logger.error( "API::remove_ca: CA Certificate '{}' not found : {}".format( cert_id, e)) return JsonResponse({ 'status': 0, 'error': "CA Certificate '{}' not found : {}".format(cert_id, str(e)) }) # Delete the certificate on disk certificate_path = "{}/{}.crt".format(certs_dir, str(cert_id)) try: os_remove(certificate_path) except Exception as e: logger.error( "API::remove_ca: Failed to delete certificate '{}' on disk : {}". format(certificate_path, str(e))) os_system("/usr/local/bin/c_rehash /home/vlt-sys/Engine/conf/certs") logger.info("API::remove_ca: Ca certificate successfully deleted on disk") return JsonResponse({'status': 1})
def doMSA(finallistfile, outdir): outfile = os_path.join(outdir, "sequences.score_ascii") outfile_html = os_path.join(outdir, "sequences.score_ascii.score_html") outfile_aln = os_path.join(outdir, "sequences.score_ascii.fasta_aln") align_html = os_path.join(outdir, "sequences_score.html") align_fasta = os_path.join(outdir, "sequences_aln.fasta") treefile = os_path.join(outdir, "sequences.dnd") args = ( "t_coffee -in {0} -mode quickaln -output=score_ascii,fasta_aln,score_html -outfile " .format(finallistfile) + outfile + " -newtree " + treefile) os_system(args) if os_path.exists(outfile_html): os_rename(outfile_html, align_html) if os_path.exists(outfile_aln): os_rename(outfile_aln, align_fasta) f = open(outfile, "r") cons = {} for line in f: if " : " in line: splitdata = line.split() upid = splitdata[0] if len(upid.split('|')) > 1: upid = upid.split('|')[1] elif len(upid.split('_')) > 1: upid = upid.split('_')[0] score = splitdata[2] cons[upid] = score return cons
def test(self): prevOK = self.testOK link = 'down' for iface in self.get_iface_list(): if 'lo' in iface: continue if os_path.exists('/sys/class/net/%s/operstate' % iface): fd = open('/sys/class/net/%s/operstate' % iface, 'r') link = fd.read().strip() fd.close() if link != 'down': break if link != 'down': s = socket(AF_INET, SOCK_STREAM) s.settimeout(self.testTime) try: self.testOK = not bool(s.connect_ex((self.testHost, self.testPort))) except: self.testOK = False s.close() else: self.testOK = False if prevOK != self.testOK: self.downstream_elements.changed((self.CHANGED_POLL,)) if prevOK and self.failCmd: os_system('/bin/sh -c "%s" &' % self.failCmd)
def __init__(self, session, MenuFolder = "" , MenuFile = '_MenuItems'): self.myList = [] self.list = [] self.myPath = MenuFolder self.MenuFile = MenuFile self.SkryptOpcji = "" self.PIC = "" picHeight = 0 if pathExists("%s/_MenuGenerator.sh" % self.myPath) is True: os_system( "%s/_MenuGenerator.sh %s" % (self.myPath, self.myPath) ) MyTitle = "" if pathExists("%s/%s" % (self.myPath,self.MenuFile) ) is True: with open ("%s/%s" % (self.myPath,self.MenuFile), "r") as myMenufile: for MenuItem in myMenufile: MenuItem = MenuItem.rstrip('\n') if not MenuItem or MenuItem[0] == '#': #omijamy komentarze continue if MenuItem[0:5] == "MENU|": MyTitle = MenuItem.replace("MENU|","") elif MenuItem[0:4] == "PIC|": if pathExists( MenuItem.replace("PIC|","") ) is True: self.PIC = MenuItem.replace("PIC|","") picHeight = 236 elif MenuItem[0:5] == "ITEM|": #teraz nierzemy pod uwage tylko te linie co mają odpowiednią ilość | #print MenuItem skladniki = MenuItem.replace("ITEM|","").split('|') if len(skladniki) != 3: continue (NazwaOpcji, TypOpcji, self.SkryptOpcji) = skladniki if NazwaOpcji != "": NazwaOpcji = _(NazwaOpcji) self.myList.append( (NazwaOpcji, TypOpcji, self.SkryptOpcji) ) self.list.append( NazwaOpcji ) myMenufile.close() ListWidth = 480 ListHeight = (len(self.list) + 1) * 22 if ListHeight + 30 + picHeight > 600: ListHeight = 600 - 30 - picHeight skin = """<screen name="myMenu" position="center,center" size="%d,%d" title="%s" >\n""" % (ListWidth, ListHeight + 30 + picHeight, _(MyTitle) ) skin += """<widget name="list" position="0,0" size="%d,%d" scrollbarMode="showOnDemand" />\n""" % (ListWidth, ListHeight + 30) skin += """<widget name="cover" zPosition="4" position="0,%d" size="420,236" transparent="1" alphatest="blend" />""" % (ListHeight + 30) skin += """</screen>""" self["cover"] = Cover2() self.skin = skin self.session = session Screen.__init__(self, session) self["list"] = MenuList(self.list) self["actions"] = ActionMap(["OkCancelActions"], {"ok": self.run, "cancel": self.close}, -1) self.onLayoutFinish.append(self.onStart) self.visible = True
def cmdData(self, data): if self.cache is None: self.cache = data else: self.cache += data if '\n' in data: splitcache = self.cache.split('\n') if self.cache[-1] == '\n': iteration = splitcache self.cache = None else: iteration = splitcache[:-1] self.cache = splitcache[-1] for mydata in iteration: if mydata != '': cmd = "echo '%s' >> /tmp/ipkinstall.log" % mydata os_system(cmd) if mydata.find('Downloading') == 0: pkg = mydata.split(' ', 5)[1].strip() pkgname = str(os_path.basename(pkg)) self.currentpkgname = pkgname.split('_')[0] self['package'].setText(self.currentpkgname) self['status'].setText(_('Downloading') + '...') self.count_success = self.count_success + 1 elif mydata.find('Upgrading') == 0: self.currentpkgname = mydata.split(' ', 8)[1].strip() pkgfrom = mydata.split(' ', 8)[5].strip() pkgto = mydata.split(' ', 8)[7].strip() self['package'].setText(self.currentpkgname) self['status'].setText(_('Upgrading from %s to %s') % (pkgfrom, pkgto)) elif mydata.find('Installing') == 0: self.currentpkgname = mydata.split(' ', 5)[1].strip() self['package'].setText(self.currentpkgname) self['status'].setText(_('Installing to root...')) elif mydata.find('Removing') == 0: self.currentpkgname = mydata.split(' ', 5)[1].strip() self['package'].setText(self.currentpkgname) self['status'].setText(_('Removing from root...')) elif mydata.find('Configuring') == 0: self.currentpkgname = mydata.split(' ', 2)[1].strip() self['status'].setText('Configuring...') elif mydata.find('No packages removed') == 0: self['status'].setText(mydata) self.errormessage = mydata elif mydata.find('Collected errors:') == 0: self['status'].setText(_('Cannot install package')) self.errormessage = mydata elif mydata.find('An error occurred') == 0: self['status'].setText(_('An error occurred')) self.errormessage = mydata elif mydata.find('Failed to download') == 0: self['status'].setText(_('Failed to download')) self.errormessage = mydata elif mydata.find('opkg_download:') == 0: self['status'].setText(_('opkg_download: ERROR')) self.errormessage = mydata elif mydata.find(" Configuration file '") >= 0: self['package'].setText(mydata.split(" '", 1)[1][:-1]) self['status'].setText(mydata.replace(' ', ''))
def remove_dir(d): """ I do not know why "shutil.rmtree" does not work Remove the given directory with all its files :param d: path to the directory """ if path.isdir(d): os_system("rm -rf " + str(d))
def refreshLists_firstRun_doWeHaveNetwork( result, retval, extra_args = None): printDEBUG( "refreshLists_firstRun_doWeHaveNetwork" , "retval:%i" % retval ) if retval != 0: errorMENU(991) else: if pathExists('/var/lib/opkg/lock'): os_system('killall -9 opkg 2>/dev/null;killall -9 wget 2>/dev/null;sleep 1') self.Console.ePopen('opkg update', refreshLists_opkg_update )
def getMediaPath(): #################### for media in ['/media/%s' % x for x in os.listdir('/media')]: if not "downloaded_images" in os.listdir(media): os_system('mkdir /%s/downloaded_images' % media) if "downloaded_images" in os.listdir(media): media = os.path.join(media, "downloaded_images") print 'Media: ', media
def top(self): from time import sleep as time_sleep while True: os_system(config.command_clear) self.list_currently_working_processes( config.ps_command, config.column_with_pid_for_ps_command) self.check_processes() time_sleep(config.refresh_interwal_in_seconds)
def restoreOriginal(self): """ restoring original mvis from the backuped mvi in the plugindir""" global plugin_path for target in self.targets: file = target[1].split("/")[-1] if os_path.isfile(plugin_path + "/" + file) is True: print "restoring original ", target[0], " from ", plugin_path + "/" + file, "to", target[1] os_system("cp '%s' '%s'" % (plugin_path + "/" + file, target[1]))
def do_change_mod(self, answer): answer = answer and answer[1] # sourceDir = dirsource.getCurrentDirectory() #self.SOURCELIST.getCurrentDirectory() if answer == "CHMOD644": os_system("chmod 644 " + self.longname) elif answer == "CHMOD755": os_system("chmod 755 " + self.longname) self.doRefresh()
def raus(self): os_system("rm -f /tmp/bild") config.plugins.ORFteletext.startHZ.value = self.seite config.plugins.ORFteletext.startNZ.value = self.subseite config.plugins.ORFteletext.adr.save() config.plugins.ORFteletext.startHZ.save() config.plugins.ORFteletext.startNZ.save() self.close()
def check_backup(self): """ if a copy of the original file is not found in the plugindir, backup them """ global plugin_path for target in self.targets: file = target[1].split("/")[-1] if os_path.isfile(plugin_path + file) is not True: print "backing up original ", target[0], " from ", file os_system("cp '%s' '%s'" % (target[1], plugin_path + "/" + file))
def clickbtn_openDir(self): if self.switchType == EXCEL_LOCATION: openDir = self.excelDir else: openDir = self.profilesDir if openDir != '': openDir = os_path_normpath(openDir) os_system("explorer.exe %s" % openDir)
def restoreOriginal(self): """ restoring original mvis from the backuped mvi in the plugindir""" global plugin_path for target in self.targets: file = target[1].split("/")[-1] if os_path.isfile(plugin_path+"/"+file) is True: print "restoring original ",target[0]," from ",plugin_path+"/"+file,"to",target[1] os_system("cp '%s' '%s'" %(plugin_path+"/"+file,target[1]))
def check_backup(self): """ if a copy of the original file is not found in the plugindir, backup them """ global plugin_path for target in self.targets: file = target[1].split("/")[-1] if os_path.isfile(plugin_path+file) is not True: print "backing up original ",target[0]," from ",file os_system("cp '%s' '%s'" %(target[1],plugin_path+"/"+file))
def _clear_screen(self): """ Clear the command window/terminal using the proper clear command """ if os_name == GameUI.CLEAR_COMMAND_WINDOWS_NAME: os_system(GameUI.CLEAR_COMMAND_WINDOWS) else: os_system(GameUI.CLEAR_COMMAND_OTHER)
def autostart(reason, **kwargs): if reason == 0: print "[HyperionControl] start" #if hyperionaml is active restart hyperionaml service on start e2 os_system("systemctl -q is-active hyperionaml && systemctl restart hyperionaml") if reason == 1: print "[HyperionControl] shutdown" #stop hyperion service on shutdown (led's off) os_system("systemctl stop hyperion")
def backstage_open_new_tmux_page(page_name: str): """ 后台开启tmux page :param page_name: :return: """ # 重复开会报 # duplicate session: xxx[窗口名] os_system('tmux new -s {page_name} -d'.format(page_name=page_name, ))
def checkforInterface(self, iface): if self.getAdapterAttribute(iface, 'up') is True: return True else: ret = os_system("ifconfig %s up" % iface) os_system("ifconfig %s down" % iface) if ret == 0: return True else: return False
def send_cmd_2_tmux_page_by_page_name(page_name: str, target_cmd: str): """ 根据page_name给窗口发送命令 :param page_name: :return: """ os_system('tmux send -t "{page_name}" "{target_cmd}" Enter'.format( page_name=page_name, target_cmd=target_cmd, ))
def keyYellow(self): if self.BlockedInput == True: return printDEBUG( "keyYellow" , "starting MenuOPKGsettings" ) MenuFolder=resolveFilename(SCOPE_PLUGINS, 'Extensions/GOSmanager/MenuOPKGsettings') if pathExists( "%s/_MenuGenerator.sh" % MenuFolder) is True: os_system( "%s/_MenuGenerator.sh %s" % (MenuFolder, MenuFolder) ) if pathExists("%s/_MenuItems" % MenuFolder ) is True: from GOSmenu import myMenu self.session.openWithCallback(self.keyYellowEnd(), myMenu, MenuFolder = MenuFolder)
def setDirectory(self): #---> #- self.directory = resolveFilename(SCOPE_DEFAULTPARTITIONMOUNTDIR) #---< #+++> self.directory = resolveFilename(SCOPE_DEFAULTDIR) #+++< self.xmlfile = "defaultwizard.xml" if self.directory: os_system("mount %s %s" % (resolveFilename(SCOPE_DEFAULTPARTITION), self.directory))
def callbackExecDelete(self, answer): if answer is True: DELfilename = self['myliste'].getCurrentDirectory() + self['myliste'].getFilename() order = 'rm -f "' + DELfilename + '"' try: os_system(order) self['myliste'].refresh() except: dei = self.session.open(MessageBox, _('%s \nFAILED!' % order), MessageBox.TYPE_ERROR) dei.setTitle(_('Manipulate Files')) self['myliste'].refresh()
def callbackDelDir(self, answer): if answer is True: DELDIR = self['myliste'].getSelection()[0] order = 'rm -r "' + DELDIR + '"' try: os_system(order) self['myliste'].refresh() except: dei = self.session.open(MessageBox, _('%s \nFAILED!' % order), MessageBox.TYPE_ERROR) dei.setTitle(_('Manipulate Files')) self['myliste'].refresh()
def updateInstall(self, status): print '[Language downloader] status: %s' % status if os_path.exists('/tmp/.restart_e2'): os_remove('/tmp/.restart_e2') cmd = 'touch ' + tslang_changed os_system(cmd) idx = self['list'].getIndex() item = self.ipkList[idx][0] self.ipkList[idx] = (item, self.greenStatus) self['list'].updateList(self.ipkList) self.getfreespace()
def reloadHddTemp(self, host="127.0.0.1", port=7634, devices="all", updatetime=60, update=True): self.__host = host self.__port = port self.__devices = devices self.__updatetime = updatetime os_system("killall -9 hddtemp") ret = self.loadHddTemp() if update: self.__updateHddTempData() return ret
def responseFailed(self, failure_instance = None, error_message = ''): print '[TS multInstaller] Download failed --> %s' % error_message self.error_message = error_message if error_message == '' and failure_instance is not None: self.error_message = failure_instance.getErrorMessage() self['status'].setText(self.error_message) cmd = "echo '%s' >> /tmp/ipkinstall.log" % self.error_message os_system(cmd) self.setTitle(_('Download failed')) if os_path.exists(self.target): os_remove(self.target) self.count_failed_install = self.count_failed_install + 1 self.currentIndex = self.currentIndex + 1 self.tryNextPackage()
def gameloop(check): global input_thread while True: os_system(CLEAR_SCREEN) printScreen() if input_thread == None or not input_thread.isAlive(): input_thread = Thread(target=getMove) input_thread.start() time_sleep(0.3) if check >= 8: createFood() check = 0 nextSnakePos(_NEXT_MOVE,_PREV_MOVE) check += 1
def ManageHostsAndCategories(HostName, CategoryName = ''): printDEBUG("j00zekToolSet:ManageHostsAndCategories > HostName=%s,CategoryName=%s" %(HostName, CategoryName)) ClearMemory() hostsDir='%s/hosts' % PluginPath categoryDir='%s/hosts/%s' % (PluginPath,CategoryName) #first delete, when exists if os_path.exists('%s/%s.py' %(categoryDir,HostName[:-4])) or os_path.exists('%s/%s' %(categoryDir,HostName)): print "Removing %s from category %s" % (HostName,CategoryName) os_system('rm -rf %s/%s*' % (categoryDir,HostName[:-4]) ) #assign to category elif os_path.exists('%s/%s' %(hostsDir,HostName)): print "Assigning %s to category %s" % (HostName,CategoryName) os_system('ln -sf %s/%s %s/%s' % ( hostsDir, HostName, categoryDir, HostName) ) else: print "unknown " + hostsDir + HostName
def callbackNewFile(self, answer): if answer is None: return dest = self["filelist"].getCurrentDirectory() if (" " in answer) or (" " in dest) or (answer==""): msg = self.session.open(MessageBox,_("File name error !"), MessageBox.TYPE_ERROR, windowTitle=_("Dream-Explorer")) return else: order = 'touch ' + dest + answer try: if not fileExists(dest + answer): os_system(order) self["filelist"].refresh() except: msg = self.session.open(MessageBox,_("%s \nfailed!" % order), MessageBox.TYPE_ERROR, windowTitle=_("Dream-Explorer")) self["filelist"].refresh()
def system(logger, command): logger.info("Run command: %r" % command) exit_code = os_system(command) if not exit_code: return raise RuntimeError("Unable to run command %r (error %r)" % ( command, exit_code))
def save(self): plugin = self["list"].l.getCurrentSelection()[0] plugin.icon = None if not fileExists("/usr/lib/enigma2/python/Plugins/Extensions/EasyMedia/" + plugin.name + ".plug"): try: outf = open(("/usr/lib/enigma2/python/Plugins/Extensions/EasyMedia/" + plugin.name + ".plug"), 'wb') pickle.dump(plugin, outf) outf.close() self.session.open(MessageBox, text = (plugin.name + _(" added to EasyMedia")), type = MessageBox.TYPE_INFO) except: self.session.open(MessageBox, text = "Write Error!", type = MessageBox.TYPE_WARNING) else: order = 'rm -f \"' + '/usr/lib/enigma2/python/Plugins/Extensions/EasyMedia/' + plugin.name + '.plug' + '\"' try: os_system(order) self.session.open(MessageBox, text = (plugin.name + _(" removed from EasyMedia")), type = MessageBox.TYPE_INFO) except: self.session.open(MessageBox, text = "Write Error!", type = MessageBox.TYPE_WARNING)
def lade2(self, hs, ns): os_system("rm -f /tmp/bild") hz = str(hs) lz = hz[0] nz = str(ns) if config.plugins.ORFteletext.adr.value == "ORF": adr = "http://teletext.orf.at/" + lz + "00/" + hz + "_000" + nz + ".png" elif config.plugins.ORFteletext.adr.value == "SAT1": adr = "http://www.sat1.at/service/teletext/cache_de/" + hz + "_0" + nz + ".png" neu = "wget -O /tmp/bild " + adr self["seite"].setText(hz+"-"+nz+" at "+config.plugins.ORFteletext.adr.value) os_system(neu) if fileExists("/tmp/bild"): self.whatPic = "/tmp/bild" else: self.whatPic = eEnv.resolve("${libdir}/enigma2/python/Plugins/Extensions/ORFteletext/nodata.png") self.Show_Picture()
def deflateOnClosed(self, retval): self.container.appClosed.remove(self.deflateOnClosed) self.container.dataAvail.remove(self.cmdData) if os_path.exists(self.target): os_remove(self.target) if self.errormessage == '': self.count_success = self.count_success + 1 if self.currentpkgname.startswith('enigma2-skin-'): if not os_path.exists('/tmp/.newskin'): cmd = 'touch /tmp/.newskin' os_system(cmd) elif not os_path.exists('/tmp/.restart_e2'): cmd = 'touch /tmp/.restart_e2' os_system(cmd) else: self.count_failed_install = self.count_failed_install + 1 self.currentIndex = self.currentIndex + 1 self.tryNextPackage()
def main(): while True: os_system(CLEAR_SCREEN) raw_input(START_MSG) try: gameloop(7) except Warning: os_system(CLEAR_SCREEN) print "\r" + _GAME_OVER print "\rYou lost!(press %s)" % _NEXT_MOVE while input_thread.isAlive(): continue a = raw_input("\rWant to play again?(y/n)") if a.lower().startswith("y"): reset() continue else: sys_exit(0)
def checkStoragePath(self): tmppath = config.mediaportal.storagepath.value if tmppath != "/tmp" and tmppath != "/media/ba": if os_path.islink(tmppath): tmppath = os_readlink(tmppath) loopcount = 0 while not os_path.ismount(tmppath): loopcount += 1 tmppath = os_path.dirname(tmppath) if tmppath == "/" or tmppath == "" or loopcount > 50: self.session.open(MessageBoxExt, _("Error: Can not create cache-folders inside flash memory. Check your Cache-Folder Settings!"), type=MessageBoxExt.TYPE_INFO, timeout=20) return False os_system("mkdir -p "+config.mediaportal.storagepath.value) if not os_path.exists(config.mediaportal.storagepath.value): self.session.open(MessageBoxExt, _("Error: No write permission to create cache-folders. Check your Cache-Folder Settings!"), type=MessageBoxExt.TYPE_INFO, timeout=20) return False else: return True
def removeConf(self,extra_args): printDebugMsg("removeConf") if fileExists("/etc/hostapd.conf", 0): os_system("mv /etc/hostapd.conf /etc/hostapd.conf.linuxap.back") fp = file("/etc/network/interfaces", 'w') fp.write("# automatically generated by AP Setup Plugin\n# do NOT change manually!\n\n") fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") # eth0 setup fp.write("auto eth0\n") if apModeConfig.usedhcp.value is True: fp.write("iface eth0 inet dhcp\n") else: fp.write("iface eth0 inet static\n") fp.write(" address %d.%d.%d.%d\n" % tuple(apModeConfig.address.value) ) fp.write(" netmask %d.%d.%d.%d\n" % tuple(apModeConfig.netmask.value) ) fp.write(" gateway %d.%d.%d.%d\n" % tuple(apModeConfig.gateway.value) ) fp.close() self.setIpForward(0) self.networkRestart_start()
def myExecute(cmd, session, test=False): if test: from time import sleep sleep(5) result = 0 else: res = os_system(cmd) result = (res >> 8) print "[eParted]", result, cmd if result != 0 and session is not None: session.open(MessageBox, _("Error command '%s'") % cmd, MessageBox.TYPE_ERROR, timeout=8) return result
def addSkinToBackupDirs(self): from os import system as os_system, path as os_path # if not default skin if os_system("grep config.skin.primary_skin /etc/enigma2/settings 1>/dev/null") == 0 and config.skin.primary_skin.value != "skin.xml": skinName = config.skin.primary_skin.value[:-9] skinDir = "/usr/share/enigma2/%s" % skinName skinFiles = skinDir + "/.skin_files" if os_path.exists(skinFiles): print "maybe skin from backup, not from opkg" else: if os_system("grep %s /usr/lib/opkg/info/*.list 1>/dev/null" % skinName) == 0: os_system("opkg files `opkg search %s | awk '{print $1}'` > %s" % ("/usr/share/enigma2/"+config.skin.primary_skin.value, skinFiles)) self.backupdirs = self.backupdirs + " " + skinFiles else: print "skin is not from backup and not from opkg, can not know skin files" return self.backupdirs = self.backupdirs + " " + skinDir for line in open(skinFiles).readlines(): if os_path.exists(line.split("\n")[0]) and not line.startswith(skinDir): self.backupdirs = self.backupdirs + " " + line.split("\n")[0]