Beispiel #1
1
def startfile(filepath, operation="open"):
    """os.startfile / g_app_info_launch_default_for_uri compat

    This has the similar semantics to os.startfile, where it's
    supported: it launches the given file or folder path with the
    default app. On Windows, operation can be set to "edit" to use the
    default editor for a file. The operation parameter is ignored on
    other systems, and GIO's equivalent routine is used.

    The relevant app is started in the background, and there are no
    means for getting its pid.

    """
    try:
        if os.name == 'nt':
            os.startfile(filepath, operation) # raises: WindowsError
        else:
            uri = GLib.filename_to_uri(filepath)
            Gio.app_info_launch_default_for_uri(uri, None) # raises: GError
        return True
    except:
        logger.exception(
            "Failed to launch the default application for %r (op=%r)",
            filepath,
            operation,
        )
        return False
Beispiel #2
0
 def checkIconsAvailability(self):
     import pandas as pd
     import xlsxwriter
     import Katana
     data = self.getData()
     icons = {}
     repo_path = str(QtGui.QFileDialog.getExistingDirectory(self, "Select the repository folder.", os.getcwd(), 
                                                 QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks))
     if not repo_path:
         repo_path = os.path.join(os.getcwd(), "Images","Repository")
     for fsn_row in self.getData():
         category = fsn_row["Category"]
         for key in fsn_row.keys():
             if "Attribute" in key:
                 attribute = fsn_row[key].strip()
                 if attribute.strip() != "":
                     icon_status, folders = Katana.checkIcon(attribute, category, repository_path=repo_path)
                     if attribute not in icons.keys():
                         icons[attribute] = {
                                     "Category": category,
                                     "Icon in Folder(s)": folders
                         }
                     else:
                         if category not in icons[attribute]["Category"]:
                             icons[attribute]["Category"] = icons[attribute]["Category"] + ", "  +category
                         icons[attribute]["Icon in Folder(s)"] = [folder for folder in list(set(icons[attribute]["Icon in Folder(s)"] + folders)) if len(folder)>0]
     icons_data_frame = pd.DataFrame.from_dict(icons)
     icons_data_frame = icons_data_frame.apply(self.getMeaningfulPathText,axis=0)
     file_path = os.path.join(os.getcwd(),"cache","Icon_Search_Results_%s.csv"%datetime.datetime.now().strftime("%y%m%d_%H%M%S"))
     #file_handler = pd.ExcelWriter(file_path,engine="xlsxwriter")
     icons_data_frame.T.to_csv(file_path)
     os.startfile(file_path,"open")
Beispiel #3
0
def open_file(fname):
    if sys.platform.startswith('darwin'):
        subprocess.call(('open', fname))
    elif os.name == 'nt':
        os.startfile(fname)
    elif os.name == 'posix':
        subprocess.call(('xdg-open', fname))
def showQRImage():
    global tip

    url = 'https://login.weixin.qq.com/qrcode/' + uuid
    params = {
        't': 'webwx',
        '_': int(time.time()),
    }

    r = myRequests.get(url=url, params=params)

    tip = 1

    f = open(QRImagePath, 'wb')
    f.write(r.content)
    f.close()
    time.sleep(1)

    if sys.platform.find('darwin') >= 0:
        subprocess.call(['open', QRImagePath])
    elif sys.platform.find('linux') >= 0:
        subprocess.call(['xdg-open', QRImagePath])
    else:
        os.startfile(QRImagePath)

    print('请使用微信扫描二维码以登录')
Beispiel #5
0
 def exportData(self):
     import pandas as pd
     import xlsxwriter
     #Get the output location.
     output_path = str(QtGui.QFileDialog.getExistingDirectory(self, "Select the output folder.", os.getcwd(), 
                                                 QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks))
     #Calculate the different types of FSNs based on prefix.
     if output_path:
         file_path = os.path.join(output_path,"flipkart_data_%s.xlsx"%datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
         file_handler = pd.ExcelWriter(file_path,engine="xlsxwriter")
         fsns_list = self.data_from_fk.keys()
         prefixes = list(set([fsn[:3] for fsn in fsns_list]))
         prefixes.sort()
         seggregated_data_set = {}
         #Split data based on FSN prefix.
         for prefix in prefixes:
             valid_fsns = [fsn for fsn in fsns_list if prefix==fsn[:3]]
             seggregated_data_set[prefix] = {}
             for fsn in valid_fsns:
                 seggregated_data_set[prefix][fsn] = self.data_from_fk[fsn]
             #Create dataframes for each data set.
             prefix_data_set = pd.DataFrame.from_dict(seggregated_data_set[prefix])
             #Save the dataframe in an excel file with the entire dataset in one sheet, 
             #and individual sheets containing prefix-wise data, stored in the output folder.
             prefix_data_set.T.to_excel(file_handler, prefix)
         file_handler.save()
     pd.DataFrame.from_dict(self.data_from_fk).T.to_csv(os.path.join(output_path,"flipkart_data_%s.csv"%datetime.datetime.now().strftime("%Y%m%d_%H%M%S")))
     os.startfile(file_path,"open")
     self.sendAlert("Success","Success exported data for %d possible verticals into %s."%(len(prefixes),os.path.basename(file_path)))
Beispiel #6
0
def Main():
    restart_reload = False
    try:
        w = Translator( "Translator-Main.xml", CWD )
        w.doModal()
        restart_reload = w.RestartXBMC_ReloadLanguage
        del w
    except:
        print_exc()
    xbmc.executebuiltin( "Dialog.Close(busydialog)" )

    if restart_reload:
        choices = [ "Restart XBMC", "Reload Language", "Close Dialog" ]
        selected = xbmcgui.Dialog().select( "XBMC language file has been changed!", choices )
        if selected == 0:
            if not UNDER_XBOX:
                xbmc.executebuiltin( "XBMC.Minimize()" )
            xbmc.executebuiltin( "XBMC.RestartApp()" )
            if os.environ.get( "OS", "win32" ) == "win32":
                os.startfile( os.path.join( CWD, "resources", "RestartXBMC", "windows.bat" ) )

        elif selected == 1:
            xbmc.executebuiltin( "ActivateWindow(appearancesettings)" )
            xbmc.sleep( 100 )
            xbmc.executebuiltin( "SetFocus(-99)" )
            xbmc.executebuiltin( "SetFocus(-80)" )

        else:
            xbmcgui.Dialog().ok( "XBMC Translator", "XBMC requires to restart to change your language.", "Or reload language." )
def showQRImage():
    global tip

    url = 'https://login.weixin.qq.com/qrcode/' + uuid
    params = {
        't': 'webwx',
        '_': int(time.time()),
    }

    request = getRequest(url=url, data=urlencode(params))
    response = wdf_urllib.urlopen(request)

    tip = 1

    f = open(QRImagePath, 'wb')
    f.write(response.read())
    f.close()

    if sys.platform.find('darwin') >= 0:
        subprocess.call(['open', QRImagePath])
    elif sys.platform.find('linux') >= 0:
        subprocess.call(['xdg-open', QRImagePath])
    else:
        os.startfile(QRImagePath)

    print('请使用微信扫描二维码以登录')
 def openFolder(self, path):
     if os.name == 'nt':
         os.startfile(path)
     elif os.name == 'posix':
         os.system('xdg-open "%s"' % path)
     elif os.name =='os2':
         os.system('open "%s"' % path)
Beispiel #9
0
def open_file(path):
    if platform.system() == "Windows":
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])
Beispiel #10
0
    def open_file_with_default_application(file_path):
        """
        Launch a program to open an arbitrary file. The file will be opened using 
        whatever program is configured on the host as the default program for that 
        type of file.
        """

        norm_path = os.path.normpath(file_path)

        if not os.path.exists(norm_path):
            print("%s does not exist" % file_path)
            return

        if os.sys.platform == "win32":
            try:
                os.startfile(norm_path)
            except WindowsError as msg:
                print("Error Opening File. " + str(msg))
        else:
            search = os.environ["PATH"].split(":")
            for path in search:
                prog = os.path.join(path, "xdg-open")
                if os.path.isfile(prog):
                    os.spawnvpe(os.P_NOWAIT, prog, [prog, norm_path], os.environ)
                    return
Beispiel #11
0
    def key_manager(self, event):

        logger.debug('get key %s', event.KeyID)
        key_id = str(event.KeyID)
        # if not self.IS_RUN:
        #     return True
        has_key = len(self.KEY_LIST)

        if has_key == 0 and key_id == self.key_1:
            self.KEY_LIST.append(self.key_1)
            return True
        if has_key == 1:
            if key_id == self.key_2:
                self.KEY_LIST.append(self.key_2)
            return True

        if (has_key == 2) and(key_id in self.user_info):
            flag = self.user_info[key_id]['flag']
            cmd = self.user_info[key_id]['cmd']

            if flag:
                subprocess.Popen(args=cmd, shell=True)
            else:
                os.startfile(cmd)

            self.KEY_LIST[:] = ()
        return True
Beispiel #12
0
def main(args):
    logging.basicConfig(level=logging.DEBUG)
    instanceName = '{5A475CB1-CDB5-46b5-B221-4E36602FC47E}'
    myapp = SingleInstance(instanceName)
    try:
        if myapp.alreadyRunning():
            logging.info('another instance of sync tool already running')

        if len(args)>0:
            upgradeHost = args[0]
        else:
            upgradeHost = "www.digitalpanda.co.za"

        logging.debug('upgradeHost is: %s' % upgradeHost)
        autoUpdate = AutoUpdate(None, upgradeHost)
        if (autoUpdate.IsInstalled()):
            logging.debug('panda already installed - start...')
            #pandaPath = autoUpdate.GetShortcutPath()
            #subprocess.call([pandaPath])
            os.startfile(autoUpdate.GetShortcutPath())
        else:
            logging.debug('panda not installed - starting install')
            InstallPanda(upgradeHost)
    finally:
        del myapp
Beispiel #13
0
 def Smart_Input(self, msg='(Y/N)'):
     """ Extended raw_input with system functions"""
     while True:
         Out = raw_input(msg)
         OutUp = Out.upper()
         LOO = len(Out)
         path = Out[2:].strip(' ') ## Used for "CD"
         if path.upper() in ["HOME"]: path = _ScriptLoc
         if OutUp in self.ExitCode and len(Out)==4:
             raise SystemExit
         elif OutUp in ["LS", "DIR"]:
             print _Fancy, os.listdir('.')
         elif OutUp in ["GWD", "PWD"]:
             print _Fancy, os.getcwd()
         elif OutUp in ["FAQ", "HELP"]:
             print _Fancy, FAQ
         elif OutUp in "GETINFO":
             self.GetDetails()
         elif OutUp in ["START", "OPEN"]:
             os.startfile('.')
         elif OutUp == "LOGOUT":
             raise EnvironmentError
         elif OutUp[:2]=="CD" and self.Exists(path):
             os.chdir(path)
             print "\nChanging directories to: \n%s \n" % os.getcwd()
         else:
             return Out
Beispiel #14
0
 def open(self, url, new=0, autoraise=True):
     try:
         os.startfile('microsoft-edge:' + url)
     except WindowsError:
         return False
     else:
         return True
Beispiel #15
0
    def open_help(self, name):
        """Open the selected help file in HTML format.

        This method open the browser with the appropriate file.
        The file is the one in the user's language, unless it cannot
        be found.

        """
        lang = self.settings.get_language()
        filename = name + ".html"
        path = os.path.join("doc", lang, filename)
        if os.path.exists(path):
            self.logger.debug("Open the help file for {} (lang={})".format(
                    name, lang))
            os.startfile(path)
            return

        # Try English
        path = os.path.join("doc", "en", filename)
        if os.path.exists(path):
            self.logger.debug("Open the help file for {} (lang=en)".format(
                    name))
            os.startfile(path)
            return

        # Neither worked
        self.logger.debug("The documentation for the {} help file " \
                "cannot be found, either using lang={} or lang=en".format(
                name, lang))
Beispiel #16
0
 def on_stitch(self,*args):
     self.stat("Generating stitched image...")
     x1,y1,x2,y2=[self.adj_x1.value,self.adj_y1.value,\
                  self.adj_x2.value,self.adj_y2.value]
     squish=self.adj_squish.value
     workwith=[]
     for fname in os.listdir(self.folder):
         if ".jpg" in fname or ".bmp" in fname \
                or ".png" in fname or ".tif" in fname:
             if not "stitched" in fname and \
                not self.fname in fname:
                 workwith.append(fname)
                 print "I SEE:",self.folder,fname
     workwith.sort()
     im=Image.new("RGB",((x2-x1)*len(workwith),y2-y1))
     try:os.mkdir(self.folder+"/stitched/")
     except:pass #folder there already
     for i in range(len(workwith)):
         print "Loading",workwith[i]
         im2=Image.open(self.folder+workwith[i])
         im2=im2.crop((x1,y1,x2,y2))
         if self.togglebutton2.get_active()==True:
             self.stat("saving %03d_"%i+self.fname+"...")
             im2.save(self.folder+"/stitched/%03d_"%i+self.fname,quality=90)
         im.paste(im2,(i*(x2-x1),0))
     self.stat("saving large image...")
     im.save(self.folder+"/stitched/"+self.fname,quality=90)
     im=im.resize((im.size[0]/squish,im.size[1]),Image.ANTIALIAS)
     im.save(self.folder+"/stitched/squished_"+self.fname,quality=90)
     f=open("stitchlog.txt",'w')
     f.write(str([x1,y1,x2,y2,self.imfilename]))
     f.close()
     print "DONE"             
     self.stat("COMPLETE!!! Launching folder containing stitched images...")   
     os.startfile(self.folder+"/stitched/")
Beispiel #17
0
def to_html(data):
    if not data:
        return
    fields = data[0]._fields

    row_template = ('<tr>' + ''.join("<td>{" + f + "}</td>"
                    for f in fields) + '</tr>')
    header_footer_text = ''.join("<th>" + f + "</th>" for f in fields)

    mark_up = ["""<TABLE id="tbResultSet" class="cell-border" cellspacing="0" width="100%">"""]
    mark_up.append('<thead><TR>')
    mark_up.append(header_footer_text)
    mark_up.append('</TR></thead>')
    mark_up.append('<tfoot><TR>')
    mark_up.append(header_footer_text)
    mark_up.append('</TR></tfoot>')
    mark_up.append('<tbody>')
    for row in data:
        mark_up.append(row_template.format_map(row._asdict()))
    mark_up.append('</tbody>')
    mark_up.append("</TABLE>")

    htmlfile_handle, htmlpath = tempfile.mkstemp(".htm", text=True)
    tmp = _html_options["Template_HTML"]
    tmp = tmp.replace("{{TABLE MARK UP}}", "\n".join(mark_up))
    tmp = tmp.replace("{{SCRIPT DIR}}",
                      os.path.dirname(os.path.realpath(__file__)) +
                      "\\resources")
    print("Creating and opening temp file", htmlpath)
    with os.fdopen(htmlfile_handle, mode="w", encoding="UTF-8") as f:
        f.write(tmp)
    os.startfile(htmlpath)
Beispiel #18
0
def open_url(url):
    '''
    Opens a file with the platform's preferred method
    '''
    if url.startswith('http'):
        open_url_in_browser(url)
        return

    # Try opening the file locally
    if sys.platform == 'win32':
        try:
            if uri_is_local(url):
                url = get_local_url(url)
            logging.info('Trying to open %s with "os.startfile"' % url)
            # os.startfile is only available on windows
            os.startfile(url)
            return
        except (WindowsError, OSError):
            logging.exception('Opening %s with "os.startfile" failed' % url)

    elif sys.platform == 'darwin':
        try:
            logging.info('Trying to open %s with "open"' % url)
            system_call(['open', url])
            return
        except OSError, subprocess.CalledProcessError:
            logging.exception('Opening %s with "open" failed' % url)
Beispiel #19
0
 def handleBrowseURL(self, client, url):
     """visit the specified URL using the system browser
     
     if the URL contains %s, substitute the local webDir
     if the URL contains %t, show a temp file containing NEWS and README """
     if url.find('%t') > -1:
         release_notes = os.path.join(G.application.tempWebDir,
                 'Release_Notes.html')
         f = open(release_notes, 'wt')
         f.write('''<html><head><title>eXe Release Notes</title></head>
             <body><h1>News</h1><pre>\n''')
         try:
             news = open(os.path.join(self.config.webDir, 'NEWS'),
                     'rt').read()
             readme = open(os.path.join(self.config.webDir, 'README'),
                     'rt').read()
             f.write(news)
             f.write('</pre><hr><h1>Read Me</h1><pre>\n')
             f.write(readme)
         except IOError:
             # fail silently if we can't read either of the files
             pass
         f.write('</pre></body></html>')
         f.close()
         url = url.replace('%t', release_notes)
     else:
         url = url.replace('%s', self.config.webDir)
     log.debug(u'browseURL: ' + url)
     if hasattr(os, 'startfile'):
         os.startfile(url)
     elif sys.platform[:6] == "darwin":
         import webbrowser
         webbrowser.open(url, new=True)
     else:
         os.system("firefox " + url + "&")
Beispiel #20
0
def helpdesk():
    """Open the NEST helpdesk in browser.

    Use the system default browser.

    KEYWORDS: info
    """

    if sys.version_info < (2, 7, 8):
        print("The NEST helpdesk is only available with Python 2.7.8 or "
              "later. \n")
        return

    if 'NEST_DOC_DIR' not in os.environ:
        print(
            'NEST help needs to know where NEST is installed.'
            'Please source nest_vars.sh or define NEST_DOC_DIR manually.')
        return

    helpfile = os.path.join(os.environ['NEST_DOC_DIR'], 'help',
                            'helpindex.html')

    # Under Windows systems webbrowser.open is incomplete
    # See <https://bugs.python.org/issue8232>
    if sys.platform[:3] == "win":
        os.startfile(helpfile)

    # Under MacOs we need to ask for the browser explicitly.
    # See <https://bugs.python.org/issue30392>.
    if sys.platform[:3] == "dar":
        webbrowser.get('safari').open_new(helpfile)
    else:
        webbrowser.open_new(helpfile)
    def keyPressEvent(self, qKeyEvent):
        global remove_type
        if qKeyEvent.key() == QtCore.Qt.Key_Return:
            global opened_cases
            opened_cases.append([chosenfile, destin_file, selected_file, selected_index, selected_file.parent()])
            remove_type = 'list'
            # opened_cases[chosenfile] = selected_file
            os.startfile(chosenfile)

        if qKeyEvent.key() == QtCore.Qt.Key_Delete:
            global removed_file
            global removed_cases
            if  power == '1haveth3p0w3r' or username in poweruser_list:

                try:
                    shutil.move(chosenfile, destin_file)
                    removed_cases.append([chosenfile, destin_file, selected_file, selected_index, selected_file.parent()])
                    file_in = chosenfile
                    g = Ui_MainWindow()
                    g.db_write(file_in, 'remove')
                    t = selected_file.parent()
                    t.removeChild(selected_file)
                except:
                    pass
            else:
                pass
        elif ((qKeyEvent.key() == QtCore.Qt.Key_Up) or (qKeyEvent.key() == QtCore.Qt.Key_Down)
              or (qKeyEvent.key() == QtCore.Qt.Key_Right) or (qKeyEvent.key() == QtCore.Qt.Key_Left)):
            QtGui.QTreeView.keyPressEvent(self, qKeyEvent)
            self.get_path(self.currentItem(), self.currentIndex(), reuse_root)
Beispiel #22
0
 def startWin(self):
     try:
         import _winreg
         t = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\TorrentStream')
         needed_value =  _winreg.QueryValueEx(t , 'EnginePath')[0]
         path= needed_value.replace('tsengine.exe','')
         self.log.out("Try to start %s"%needed_value)
         self.progress.update(0,'Starting TSEngine','')
         os.startfile(needed_value)
         self.log.out('TSEngine starting')
     except: 
         try:
             import _winreg
             t = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\AceStream')
             needed_value =  _winreg.QueryValueEx(t , 'EnginePath')[0]
             path= needed_value.replace('ace_engine.exe','')
             self.log.out("Try to start %s"%needed_value)
             self.progress.update(0,'Starting ASEngine','')
             os.startfile(needed_value)
             self.log.out('ASEngine starting')
         except:
             self.sm('Not Installed')
             self.log.out('Not Installed')
             self.progress.update(0,'AceStream not installed','')
             return False
     return True
Beispiel #23
0
def printReport(path, printerName=None, printerPort=None, copies=1):
	"""Print the passed report (txt or pdf) to the default printer.

	If gsprint is installed and on the path:
		1) printerName specifies which printer to output to. (None: use default printer)
		2) printerPort specifies which port to output to. (None: use default port)
		3) multiple copies are handled more efficiently.

	NOTE: gsprint	is part of gsview, and gsview depends on ghostscript.
	These packages are GPL - to avoid legal issues make sure your end 
	user installs them separately from your application.
	"""
	if gsprint:
		args = ["gsprint", path]
		if printerName:
			args.insert(-1, '-printer')
			args.insert(-1, "%s" % printerName)
		if copies > 1:
			args.insert(-1, '-copies')
			args.insert(-1, str(copies))
		p = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
		p.communicate()
	else:
		for i in range(copies):
			if sys.platform.startswith("win"):
				os.startfile(path, "print")
			else:
				subprocess.Popen(("lpr", path))
Beispiel #24
0
 def compile(self):
     try:
         import ctypes
     except ImportError:
         try:
             import win32api
         except ImportError:
             import os
             os.startfile(self.pathname)
         else:
             print "Ok, using win32api."
             win32api.ShellExecute(0, "compile",
                                 self.pathname,
                                 None,
                                 None,
                                 0)
     else:
         print "Cool, you have ctypes installed."
         res = ctypes.windll.shell32.ShellExecuteA(0, "compile",
                               self.pathname,
                               None,
                               None,
                               0)
         if res < 32:
             raise RuntimeError, "ShellExecute failed, error %d" % res
Beispiel #25
0
    def OnSubmit(self, event):
        if self.startScreenLockCheckbox.IsChecked():
            server = os.path.join(PATH, 'screenlockServer.exe')
            key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE,
                               "Software\\Microsoft\\Windows\\CurrentVersion\\Run",0, wreg.KEY_ALL_ACCESS)
            # Create new value
            wreg.SetValueEx(key, 'startScreenlockServer', 0, wreg.REG_SZ, server)
            key.Close()

        if self.readmeCheckbox.IsChecked():
            path = self.config.get('post-install')
            os.startfile(path)
            self.logger.debug(str(datetime.now()) + ' Postinstall: post-install.txt Opened')

        if self.setPasswordCheckbox.IsChecked():
            path = self.config.get('setAdminPsw')
            self.logger.debug( str(datetime.now()) + ' Postinstall: Set Passwords Opened' )
            self.p = subprocess.Popen(path)
        try:
            if self.setCoralRadioBtn.GetValue():
                self.config.writeKey('true','coral')
                self.logger.debug( str(datetime.now()) + ' Postinstall: \'coral\' has been updated to \'true\'')
            else:
                self.config.writeKey('false','coral')
                self.logger.debug(str(datetime.now()) + ' Postinstall: \'coral\' has been updated to \'false\'')
        except Exception, e:
            self.logger.debug(str(datetime.now()) + ' Postinstall: ' + str(e))
Beispiel #26
0
def get_url(url):
    try:
        html = opener.open(url, timeout=timeout).read()
    except KeyboardInterrupt:
        # Kill program if Control-C is pressed
        sys.exit(0)
    except:
        # Restart TOR if theres a problem
        e = sys.exc_info()[0]
        if _verbose: print "ERROR: " + str(e)
        os.system('taskkill /im tor.exe')
        if _verbose: print "INFO: Restarting TOR"
        time.sleep(1)
        os.startfile(tor_exe_path)
        return ''

    # See if pastebin is complaining
    if html == pastebin_overload:
        if _verbose: print 'ERROR: Too many requests'
        time.sleep(5)
        return ''
    # If not, we are good
    elif html:
        return html
    # Tor download error, skip it and move on
    else:
        if _verbose: print 'ERROR: Download is empty - ' + url
        return ''
Beispiel #27
0
 def MostrarPDF(self, archivo, imprimir=False):
     if sys.platform.startswith(("linux2", 'java')):
         os.system("evince ""%s""" % archivo)
     else:
         operation = imprimir and "print" or ""
         os.startfile(archivo, operation)
     return True
def make_text_string(record):
    '''
    Formats text
    '''
    prefixes = get_prefixes()
    client = record[2]
    job_code = record[3]
    description = record[4]
    try:
        prefix = prefixes[client]
    except:
        startfile(r'S:\CRG Internal Files\Financial Files\01 - AMEX Statements\Arrays\Client to job prefix.xlsx')
        raise Exception('Prefix not found: ', client)
    if '-' not in prefix:
        prefix += '-'
    name = str(prefix + job_code + ' ' + description)
    name = name.replace(' and ',' & ')
    name = name.replace('publication','pub.')
    name = name.replace('Publication','Pub.')
    name = name.replace('meeting','mtg.')
    name = name.replace('Meeting','Mtg.')
    name = name.replace(':',' ')
    name = name.rstrip()
    maximum_char_len_for_quickbooks_name = 41
    return name[:maximum_char_len_for_quickbooks_name]
Beispiel #29
0
    def main(self):
        # DLリスト
        self.dlist = []
        for item in self.urlist:
            self.dlist.append(''.join(('"', item, '" ')))
            del item
        print u'ダウンロードリスト'
        for item in self.dlist:
            print item

        # バッチファイル作成
        self.batname = os.path.join(self.cwd, 'MyApp_MovieDL.bat')
        f = open(self.batname, 'w')
        f.write(self.bat.encode('cp932'))
        f.write('Getter1.exe ' )
        for item in self.dlist:
            f.write(item)
        f.write('\n')
        f.write('exit')
        f.close()

        # バッチファイル実行
        self.batf = os.path.join(self.cwd, self.batname)
        os.startfile(self.batf)
        print u'DLを開始します.'
Beispiel #30
0
def previewReport(path, modal=False):
	"""Preview the passed report (txt or pdf) file in the default viewer."""
	try:
		# On Windows, use the default viewer (probably Notepad or Adobe Acrobat)
		os.startfile(path)
	except AttributeError:
		# On Mac, use the default viewer (probably TextEdit.app or Preview.app)
		if sys.platform == "darwin":
			os.system("open %s" % path)
		else:
			# On Linux, try to find an installed viewer and just use the first one
			# found. I just don't know how to reliably get the default viewer from
			# the many distros.
			reportType = path.split(".")[-1]
			if reportType == "txt":
				viewers = ("gedit", "kate", "firefox", "mozilla-firefox", "chromium")
			elif reportType == "pdf":
				viewers = ("gpdf", "kpdf", "okular", "evince", "acroread", "xpdf", "firefox",
					"mozilla-firefox")
			else:
				raise ValueError("Unknown report type '%s'." % reportType)

			viewer = None
			for v in viewers:
				r = os.system("which %s 1> /dev/null 2> /dev/null" % v)
				if r == 0:
					viewer = v
					break

			if viewer:
				if modal:
					subprocess.call((viewer, path))
				else:
					subprocess.Popen((viewer, path))
Beispiel #31
0
def actions_invoke(res, score):
    frequency = 2500  # Set Frequency To 2500 Hertz
    duration = 1000
    global fist, two, three, four, five, status, path
    if score >= 0.6 and res == "fist":
        fist = fist + 1
        two = 0
        three = 0
        four = 0
        five = 0
        print("{} fist".format(fist))
        if (fist == 3):
            status = 'normal'
            path = app_pref1
            print("{} Invoked".format(app_pref1))
            winsound.Beep(frequency, duration)
            print("In normal mode")
            os.startfile(app_pref1)
            fist = 0
    elif score >= 0.6 and res == "two":
        two = two + 1
        fist = 0
        three = 0
        four = 0
        five = 0
        print("{} two".format(two))
        if (two == 3):
            status = 'normal'
            path = app_pref2
            print("{} invoked".format(app_pref2))
            winsound.Beep(frequency, duration)
            print("In normal mode")
            os.startfile(app_pref2)
            two = 0
    elif score >= 0.6 and res == "three":
        three = three + 1
        fist = 0
        two = 0
        four = 0
        five = 0
        print("{} three".format(three))
        if (three == 3):
            status = 'normal'
            path = app_pref3
            print("{} invoked".format(app_pref3))
            winsound.Beep(frequency, duration)
            print("In normal mode")
            os.startfile(app_pref3)
            three = 0
    elif score >= 0.6 and res == "four":
        four = four + 1
        fist = 0
        two = 0
        three = 0
        five = 0
        print("{} four".format(four))
        if (four == 3):
            status = 'normal'
            path = app_pref4
            print("{} invoked".format(app_pref4))
            winsound.Beep(frequency, duration)
            print("In normal mode")
            os.startfile(app_pref4)
            four = 0
    elif score >= 0.6 and res == "five":
        five = five + 1
        fist = 0
        two = 0
        three = 0
        four = 0
        print("{} five".format(five))
        if (five == 3):
            status = 'normal'
            path = app_pref5
            print("{} invoked".format(app_pref5))
            winsound.Beep(frequency, duration)
            print("In normal mode")
            os.startfile(app_pref5)
            five = 0
Beispiel #32
0
 def Edit(self):
     os.startfile(shutil.which('Notepad'))
Beispiel #33
0
inp = req.get(
    "http://api.openweathermap.org/data/2.5/find?q=Simferopol,UA&type=like&APPID=a50134af28c2718b67c6f87a3f126eef"
)
JSONData = inp.json()

if __name__ != "__main__":
    with open(
            r"..\server(C++)\ConsoleApplication1\ConsoleApplication1\supscripts\PublicData.json",
            "w") as f:
        js.dump(JSONData, f)
else:
    with open(r"PublicData.json", "w") as f:
        js.dump(JSONData, f)

# with open("PublicData.json", "r") as read_file:
#     UnpackData = js.load(read_file)

weather = JSONData["list"][0]["weather"][0]["main"]
temperature = JSONData["list"][0]["main"]["temp"] - 273.15

if __name__ != "__main__":
    with open(
            r"..\server(C++)\ConsoleApplication1\ConsoleApplication1\supscripts\PDataCash.txt",
            "w") as f:
        print(weather, round(temperature), file=f)
else:
    with open(r"PDataCash.txt", "w") as f:
        print(weather, round(temperature), file=f)

startfile("widgetparser.py")
Beispiel #34
0
                        jil_file.write("\n")
                        jil_file.write("\n")

                        row += 1

                    else:

                        row += 1
                        continue


xls2jil()

print "Closing the file ..."

print "\n"
print "Done!"
print "\n"

jil_file.close()

file = str(jil_file)

path = re.findall('\'(.+?)\'', file)

new_file = path[0]

os.startfile(new_file)

sleep(1.0)
Beispiel #35
0
 def start(self):
     ext = self.target.rsplit(".", 1)[-1]
     if ext.lower() == "lnk":
         os.startfile(self.target)
     else:
         assert False, "don't know how to handle target of type %s" % ext
Beispiel #36
0
    def Pressed(self):
        self.wishMe()
        self.speak("I am Jarvis,How May i help you")

        while True:
            query = self.takeCommand().lower()
            if self.counter > 5:
                break
            if 'wikipedia' in query:
                self.speak("Searching wikipedia...")
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=2)
                self.speak("According to wikipedia")
                self.speak(results)

            elif 'open youtube' in query:
                self.speak("here you go")
                try:
                    web.get('chrome').open('http://www.youtube.com')
                except:
                    web.open('http://www.youtube.com')

            elif 'open google' in query:
                self.speak("here you go")
                try:
                    web.get('chrome').open('https:\\www.google.com')
                except:
                    web.open('https:\\www.google.com')

            elif 'play music' in query:
                self.speak("have fun with music")
                music_dir = "Music"
                songs = os.listdir(music_dir)
                try:
                    os.startfile(os.path.join(music_dir, songs[0]))
                except:
                    self.speak("Add some music")

            elif 'picture' in query:
                maxTime = datetime.datetime.now() + datetime.timedelta(
                    seconds=5)
                try:
                    camera = cv2.VideoCapture(0)
                    while (datetime.datetime.now() < maxTime):
                        return_value, image = camera.read()
                        cv2.imshow('camera', image)
                        cv2.waitKey(1)
                    cv2.imwrite(
                        'Pictures\\MyPicture' +
                        str(random.randrange(0, 100000000000000000000000)) +
                        '.jpeg', image)
                    cv2.destroyAllWindows()
                    del (camera)
                except:
                    self.speak("no camara found")

            elif 'exit' in query:
                self.speak("enjoy your day!")
                break
            else:
                con = sqlite3.connect('paths.db')
                for row in con.execute('SELECT * FROM PATH'):
                    if row[0] in query:
                        try:
                            os.startfile(row[1])
                        except:
                            self.speak("invalid path, update the path")
Beispiel #37
0
 def SeeDetailSearchResult(self,event):
     self.detailNum = int(self.panelshowsearchresult.which2see.GetValue())
     os.startfile( os.getcwd()+"\\templates\\"+ self.result[self.detailNum-1][10])
Beispiel #38
0
            speak("What should I search?")
            Search_term = TakeCommand().lower()
            wb.open('https://www.google.com/search?q=' + Search_term)

        #elif 'search' in query:
        #query = query.replace("query","")
        #wb.open(query)

        elif "who am i" in query:
            speak("If you can talk, then definitely you are a human")
        elif "why you came to this world" in query:
            speak("Thanks to MAK. further it is a secret")
        elif 'word' in query:
            speak("opening MS Word")
            word = r'Word path'
            os.startfile(word)

        elif 'what is love' and 'tell me about love' in query:
            speak("It is 7th sense that destroy all other senses , "
                  "And I think it is just a mere illusion , "
                  "It is waste of time")

        elif 'empty recycle bin' in query:
            winshell.recycle_bin().empty(confirm=False,
                                         show_progress=False,
                                         sound=True)
            speak("Recycle Bin Recycled")

        elif 'send email' in query:
            try:
                speak("What should I say?")
Beispiel #39
0
    return images

imgs1 = getAllImages('./1st_folder')
imgs2 = getAllImages('./2nd_folder')

diff_path = './diff_folder/'

assert len(imgs1) == len(imgs2), "Two set sizes are not equal."

# write images to diff_folder
for i in range(len(imgs1)):
    img = ImageChops.difference(imgs1[i], imgs2[i])
    img.save('{}diff_img_{}.jpg'.format(diff_path ,i))

# open diff_folder
os.startfile(os.path.realpath(diff_path))



# diff = ImageChops.difference(img1, img2)

# if diff.getbbox():
#     diff.show()

# -------------------------------------------- Difference ----------------------------------------------------- #


# assert img1.mode == img2.mode, "Different kinds of images."
# assert img1.size == img2.size, "Different sizes."

# pairs = zip(img1.getdata(), img2.getdata())
Beispiel #40
0
    def selecticoncange(self):
        self.Filename = []
        self.available_Folders.clear()
        self.available_Folders.append('...')
        for currentitem in self.listWidget.selectedItems():
            self.path.append(currentitem.text())
            self.opening_lst.append(currentitem.text())
            if currentitem.text() != 'This PC' and len(self.path) == 1:
                self.accessed_device = True
            if currentitem.text() == 'This PC' and len(self.path) == 1:
                self.accessed_device = False
            if self.accessed_device == False:
                if currentitem.text() == '...' and len(self.path) == 2:
                    self.path.clear()
                    self.available_Folders = self.available_Device[:]
                elif currentitem.text() == '...' and len(self.path) == 3:
                    self.listWidget.clear()
                    del self.path[-1]
                    del self.path[-1]
                elif currentitem.text() == '...' and len(self.path) > 3:
                    del self.path[-1]
                    del self.path[-1]

                if len(self.path) == 1:
                    self.available_Folders = [
                        '%s:' % d for d in string.ascii_uppercase
                        if os.path.exists('%s:' % d)
                    ]
                    self.available_Folders.insert(0, '...')
                elif len(self.path) == 2:
                    self.dir_list_folder(self.path[1] + '\\')
                elif len(self.path) > 2:
                    if self.file_or_folder(currentitem.text()) == 'Folder':
                        self.dir_list_folder('\\'.join(self.path[1:]))
                    if self.file_or_folder(currentitem.text()) == 'File':
                        os.startfile('\\'.join(self.path[1:]))
            if self.accessed_device == True:
                if self.file_or_folder(currentitem.text()) == 'File':
                    self.path.remove(currentitem.text())
                if currentitem.text() == '...' and len(self.path) > 2:
                    del self.path[-1]
                    del self.path[-1]
                    self.request_message(self.path)
                elif currentitem.text() == '...' and len(self.path) == 2:
                    self.path.clear()
                    self.listWidget.clear()
                    self.available_Folders = self.available_Device[:]
                    self.change_item_listwidget(self.available_Folders)
                    self.lineEdit.setText('')

                else:
                    if self.file_or_folder(currentitem.text()) == 'Folder':
                        self.request_message(self.path)

            # if self.accessed_device == True:
        if self.accessed_device == False:
            if len(self.path) > 0:
                if self.file_or_folder(self.path[-1]) == 'Folder':
                    self.listWidget.clear()
                    self.lineEdit.setText(str('\\'.join(self.path)))
                if self.file_or_folder(self.path[-1]) == 'File':
                    del self.path[-1]
                    del self.available_Folders[-1]
            elif len(self.path) == 0 and len(self.path2) == 0:
                self.listWidget.clear()
                self.lineEdit.setText('')
            self.change_item_listwidget(self.available_Folders)
Beispiel #41
0
def graficaInstancia(textFile):
    'grafica una instancia, tanto el mapa como el grafo'
    output = open(textFile[:-3] + 'tex', 'w')
    print(
        "\\documentclass{standalone}\n\\usepackage{tikz}\n\\usetikzlibrary{decorations.pathmorphing}\n\\begin{document}\n\\begin{tikzpicture}[node distance = 0.5cm,inner sep = 2pt]\n\\tikzstyle{ann} = [fill=white,font=\scriptsize,inner sep=1pt] \n",
        file=output)

    #graficar mapa
    mapa = open(MAPA, 'r')
    c = 0
    print(
        "%c//////////////////////    dibuja mapa     ////////////////////////\n"
        % ('\u0025'),
        file=output)
    for linea in mapa:
        linea = linea.strip()
        if len(linea) == 0:
            break
        pedazo = linea.split()

        #agrega nodo
        print("\\draw (%f,%f) node (mark%d)  {};" %
              (float(pedazo[0]), float(pedazo[1]), c),
              file=output)
        c += 1
    print(
        "\n\\draw\\foreach \\i [count=\\xi from 1] in {0,...,%d}{(mark\\i) edge (mark\\xi)};\n"
        % (c - 2),
        file=output)

    print(
        "%c//////////////////////    dibuja grafo     ////////////////////////\n"
        % ('\u0025'),
        file=output)
    #leer instancia
    input = open(textFile, 'r')

    for linea in input:
        linea = linea.strip()
        if len(linea) == 0:
            break
        pedazo = linea.split()
        if pedazo[0] == 's:':  #subestaciones
            if pedazo[4] == '1':
                print(
                    "\\draw (%.2f,%.2f) node[fill=black,draw, minimum size=6pt,text=white] (n%d) {};  %csubestacion"
                    % (float(pedazo[2]), float(pedazo[3]), int(
                        pedazo[1]), '\u0025'),
                    file=output)
#                print("\tnode (e%d) [above of=n%d] {{\scriptsize %d}};" %(int(pedazo[1]),int(pedazo[1]),int(pedazo[5])),file=output)
            else:
                print(
                    "\\draw (%.2f,%.2f) node[lightgray,fill=lightgray,draw, minimum size=6pt,text=black] (n%d) {};  %csubestacion"
                    % (float(pedazo[2]), float(pedazo[3]), int(
                        pedazo[1]), '\u0025'),
                    file=output)
#                print("\tnode (e%d) [text=lightgray,above of=n%d] {{\scriptsize %d}};" %(int(pedazo[1]),int(pedazo[1]),int(pedazo[5])),file=output)
        elif pedazo[0] == 'n:':  #nodos
            if pedazo[4] == '1':
                print(
                    "\\draw (%.2f,%.2f) node[fill=black,circle,draw, minimum size=1pt] (n%d) {};  %cnodo"
                    % (float(pedazo[2]), float(pedazo[3]), int(
                        pedazo[1]), '\u0025'),
                    file=output)
#                print("\tnode (e%d) [above of=n%d] {{\scriptsize %d}};" %(int(pedazo[1]),int(pedazo[1]),int(pedazo[5])),file=output)
            else:
                print(
                    "\\draw (%.2f,%.2f) node[lightgray,fill=lightgray,dashed,circle,draw, minimum size=1pt] (n%d) {};  %cnodo"
                    % (float(pedazo[2]), float(pedazo[3]), int(
                        pedazo[1]), '\u0025'),
                    file=output)


#                print("\tnode (e%d) [text=lightgray,above of=n%d] {{\scriptsize %d}};" %(int(pedazo[1]),int(pedazo[1]),int(pedazo[5])),file=output)
        elif pedazo[0] == 'a:':  #arcos
            if pedazo[3] == '1':
                print("\\draw (n%d) edge  (n%d);" %
                      (int(pedazo[1]), int(pedazo[2])),
                      file=output)
            else:
                print("\\draw (n%d) edge[lightgray,dashed]  (n%d);" %
                      (int(pedazo[1]), int(pedazo[2])),
                      file=output)

    print("\\end{tikzpicture}\n\\end{document}", file=output)
    input.close()
    output.close()

    os.system("pdflatex " + textFile[:-3] + 'tex')
    os.startfile(textFile[:-3] + "pdf")
Beispiel #42
0
            speak(results)

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            webbrowser.open("google.com")

        elif 'open wikipedia' in query:
            webbrowser.open("wikipedia.com")

        elif 'play music' in query:
            music_dir = 'C:\\Users\\\\Music'
            songs = os.listdir(music_dir)
            print(songs)
            os.startfile(os.path.join(music_dir, songs[0]))

        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"Sir, the time is {strTime}")

        elif 'open code' in query:
            codePath = "C:\\Users\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codePath)

        elif 'email to aman' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "***********@gmail.com"
                sendEmail(to, content)
Beispiel #43
0
                return '%s(%s)' % (inputs.callback, json.dumps(d))

        if inputs.commit_id:
            if repo.head_cmmt_id != inputs.commit_id:
                d['outdated'] = True
                d['auto-sync'] = repo.auto_sync
                return '%s(%s)' % (inputs.callback, json.dumps(d))

        # ok, repo exists
        file_path = os.path.join(repo.worktree, path)
        uname = platform.platform()

        err_msg = ''
        if 'Windows' in uname:
            try:
                os.startfile(file_path)
            except WindowsError, e:
                if e.winerror == 1155:
                    # windows error 1155: no default application for this file type
                    d['no_assoc'] = True
                    try:
                        # try to open the folder instead
                        os.startfile(os.path.dirname(file_path))
                    except:
                        pass
                else:
                    err_msg = str(e)

        elif 'Linux' in uname:
            file_path = file_path.encode('utf-8')
            try:
if 'KEY FEATURES AND SUBSYSTEMS' in text:
    print 'KEY FEATURES AND SUBSYSTEMS = True'
else:
    print 'KEY FEATURES AND SUBSYSTEMS = False'

if 'PHYSICAL INTERFACES' in text:
    print 'PHYSICAL INTERFACES = True'
else:
    print 'PHYSICAL INTERFACES = False'

if 'LOGICAL INTERFACES' in text:
    print 'LOGICAL INTERFACES = True'
else:
    print 'LOGICAL INTERFACES = False'

if 'TEST OVERVIEW' in text:
    print 'TEST OVERVIEW = True'
else:
    print 'TEST OVERVIEW = False'

if 'PREVIOUS TEST EVENTS' in text:
    print 'PREVIOUS TEST EVENTS = True'
else:
    print 'PREVIOUS TEST EVENTS = False'

with open("plain_text.txt", "wb") as f:
    f.write(text.encode("utf-8"))

os.startfile("plain_text.txt")
Beispiel #45
0
# -*- coding: utf-8 -*-
"""
Created on Fri May  7 21:39:05 2021

@author: Amlan Ghosh
"""

import os
file = 'file location'
os.startfile(file)
    data['categories'] = categoriesSet2
    json.dump(data, open(outputJsonFilenameSet2, 'w'), indent=4)
    print('Finished writing json to {}'.format(outputJsonFilenameSet2))

#%% Sanity-check final set 1 .json file

from data_management.databases import sanity_check_json_db
options = sanity_check_json_db.SanityCheckOptions()
sortedCategories, data, _ = sanity_check_json_db.sanity_check_json_db(
    outputJsonFilenameSet1, options)
sortedCategories

# python sanity_check_json_db.py --bCheckImageSizes --baseDir "E:\wildlife_data\missouri_camera_traps" "E:\wildlife_data\missouri_camera_traps\missouri_camera_traps_set1.json"

#%% Generate previews

from visualization import visualize_db

output_dir = os.path.join(baseDir, 'preview')

options = visualize_db.DbVizOptions()
options.num_to_visualize = None
options.sort_by_filename = False
options.classes_to_exclude = None
options.trim_to_images_with_bboxes = True
options.parallelize_rendering = True

htmlOutputFile, _ = visualize_db.process_images(outputJsonFilenameSet1,
                                                output_dir, baseDir, options)
os.startfile(htmlOutputFile)
Beispiel #47
0
	def onBookmarks(self, evt):
		os.startfile(BOOKMARKS_FOLDER)
Enter your message : bye
Bye Ram, See you soon
>>> import os
>>> os.system('calc')
0
>>> os.getcwd()
'C:\\Users\\asus\\Documents\\Data\\DataTransfer\\BMPL_Batches\\2019\\June\\Python_WE_June_2'
>>> os.chdir("C:\Users\asus\Music")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> os.chdir(r"C:\Users\asus\Music")
>>> os.listdir()
['5-Varlaam Varlaam Vaa-SenSongsMp3.Co.mp3', 'BIGGEST BASS DROP EVER! (EXTREME BASS TEST!!!).mp3', 'Cristiano Ronaldo - Faded Best Moments 2017 • 100.000 Subscribers.mp3', 'desktop.ini', 'Dub Theri Step with Lyrics   Theri   Vijay, Samantha, Amy Jackson   Atlee   G.V.Prakash Kumar.ogg', 'Galti.mp3', 'Kaththi Theme…The Sword of Destiny - Full Audio.ogg', 'music_1.ogg', 'Na Ja.mp3', 'Shape of You.mp3', 'Street Fighter V Soundtrack - Main Menu.ogg', "Street Fighter V Soundtrack - Ryu's Theme.ogg", 'StreetFighter.mp3', 'Top 10 Tamil Mass BGM (Theme Song) 2011-2016.mp4', 'Vedalam - The Theri Theme Lyric   Ajith Kumar, Shruti Haasan   Anirudh.ogg']
>>> songs = os.listdir()
>>> import random
>>> song = random.choice(songs)
>>> os.startfile(song)
>>> song = random.choice(songs)
>>> os.startfile(song)
>>> os.startfile(song)
>>> song = random.choice(songs)
>>> os.startfile(song)
>>> import glob
>>> songs = glob.glob('*.mp3')
>>> song = random.choice(songs)
>>> os.startfile(song)
>>> songs
['5-Varlaam Varlaam Vaa-SenSongsMp3.Co.mp3', 'BIGGEST BASS DROP EVER! (EXTREME BASS TEST!!!).mp3', 'Cristiano Ronaldo - Faded Best Moments 2017 • 100.000 Subscribers.mp3', 'Galti.mp3', 'Na Ja.mp3', 'Shape of You.mp3', 'StreetFighter.mp3']
>>> songs = glob.glob('*.mp3') + glob.glob('*.ogg')
>>> songs
['5-Varlaam Varlaam Vaa-SenSongsMp3.Co.mp3', 'BIGGEST BASS DROP EVER! (EXTREME BASS TEST!!!).mp3', 'Cristiano Ronaldo - Faded Best Moments 2017 • 100.000 Subscribers.mp3', 'Galti.mp3', 'Na Ja.mp3', 'Shape of You.mp3', 'StreetFighter.mp3', 'Dub Theri Step with Lyrics   Theri   Vijay, Samantha, Amy Jackson   Atlee   G.V.Prakash Kumar.ogg', 'Kaththi Theme…The Sword of Destiny - Full Audio.ogg', 'music_1.ogg', 'Street Fighter V Soundtrack - Main Menu.ogg', "Street Fighter V Soundtrack - Ryu's Theme.ogg", 'Vedalam - The Theri Theme Lyric   Ajith Kumar, Shruti Haasan   Anirudh.ogg']
>>> 
Beispiel #49
0
os.system('cls')

print(f'{Fore.LIGHTRED_EX}ATENÇÃO!')
print(f'{Fore.WHITE}A pasta Downloads será aberta')
sleep(1)
print(f'{Fore.YELLOW}Veja se gostou das alterações')
sleep(1)
print(f'{Fore.WHITE}Se quiser desfazer as alterações, volte aqui no programa e confirme a respectiva opção')
print(f'{Fore.LIGHTRED_EX}NÃO FECHE O PROGRAMA!')
print(Style.RESET_ALL)

for c in range(5, 0, -1):
    sleep(1)
    print(f'Abrindo pasta Downloads em {c}')
    
os.startfile(pathstr)

print(f'''

        Quer manter as alterações?
        Digite '{Fore.LIGHTGREEN_EX}S{Style.RESET_ALL}' para manter as alterações
        Digite '{Fore.LIGHTRED_EX}N{Style.RESET_ALL}' para desfazer alterações
        
        As pastas vazias são temporárias e serão apagadas
        ''')

print('')

#  Bloco da opção do usuário
while True:  # Loop em caso de erros
    try:  # Tente isso
        elif "open youtube" in query:
            webbrowser.open("youtube.com")

        elif "open google" in query:
            webbrowser.open("google.com")

        elif "open stackoverflow" in query:
            webbrowser.open("stackoverflow.com")

        elif "music" in query:
            music_dir = "D:\\Music"
            songs = os.listdir(music_dir)
            # print(songs)
            music_file_index = random.randint(0, len(songs) - 1)
            os.startfile(os.path.join(
                music_dir,
                songs[music_file_index]))  # Play any random song from list

        elif "time" in query:
            strTime = datetime.datetime.now().strftime("%H : %M : %S")
            speak(f"Sir, the time is {strTime}")

        elif "code" in query:
            vsCodePath = r"C:\Users\aksha\AppData\Local\Programs\Microsoft VS Code\Code.exe"
            os.startfile(vsCodePath)

        elif "email" in query:
            try:
                speak("What Should I Say?")
                content = takeCommand()
                to = "*****@*****.**"
Beispiel #51
0
 def open(self):
     os.startfile(
         self.file_path)  # simply opens the file using the os library
Beispiel #52
0
	def onSpecificSearch(self, evt):
		os.startfile(SEARCH_FOLDER)
 def instr(self):
     startfile('..\\pdfs\\Four Probe.pdf')
Beispiel #54
0
    def build(self):
        """Build window."""
        self.setWindowTitle("MSFS Mod Manager - {}".format(
            get_version(self.appctxt)))
        self.setWindowIcon(
            QtGui.QIcon(
                self.appctxt.get_resource(os.path.join("icons", "icon.png"))))

        self.main_widget = main_widget(self, self.appctxt)
        self.main_widget.build()

        self.setCentralWidget(self.main_widget)

        main_menu = self.menuBar()
        file_menu = main_menu.addMenu("File")

        self.theme_menu_action = QtWidgets.QAction("FS Theme",
                                                   self,
                                                   checkable=True)
        self.theme_menu_action.setChecked(get_theme())
        self.theme_menu_action.triggered.connect(self.set_theme)
        file_menu.addAction(self.theme_menu_action)

        file_menu.addSeparator()

        menu_action = QtWidgets.QAction("Install Mod(s) from Archive", self)
        menu_action.triggered.connect(self.main_widget.install_archive)
        file_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Install Mod from Folder", self)
        menu_action.triggered.connect(self.main_widget.install_folder)
        file_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Uninstall Mods", self)
        menu_action.triggered.connect(self.main_widget.uninstall)
        file_menu.addAction(menu_action)

        file_menu.addSeparator()

        menu_action = QtWidgets.QAction("Create Backup", self)
        menu_action.triggered.connect(self.main_widget.create_backup)
        file_menu.addAction(menu_action)

        file_menu.addSeparator()

        menu_action = QtWidgets.QAction("Exit", self)
        menu_action.triggered.connect(self.parent.quit)
        file_menu.addAction(menu_action)

        edit_menu = main_menu.addMenu("Edit")

        menu_action = QtWidgets.QAction("Enable Selected Mods", self)
        menu_action.triggered.connect(self.main_widget.enable)
        edit_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Disable Selected Mods", self)
        menu_action.triggered.connect(self.main_widget.disable)
        edit_menu.addAction(menu_action)

        edit_menu.addSeparator()

        menu_action = QtWidgets.QAction("Change Disabled Mod Folder", self)
        menu_action.triggered.connect(self.main_widget.select_mod_install)
        edit_menu.addAction(menu_action)

        info_menu = main_menu.addMenu("Info")

        menu_action = QtWidgets.QAction("Refresh Mods", self)
        menu_action.triggered.connect(self.main_widget.refresh)
        info_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Mod Info", self)
        menu_action.triggered.connect(self.main_widget.info)
        info_menu.addAction(menu_action)

        help_menu = main_menu.addMenu("Help")

        menu_action = QtWidgets.QAction("About", self)
        menu_action.triggered.connect(self.main_widget.about)
        help_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Versions", self)
        menu_action.triggered.connect(self.main_widget.versions)
        help_menu.addAction(menu_action)

        help_menu.addSeparator()

        menu_action = QtWidgets.QAction("Open Official Website", self)
        menu_action.triggered.connect(lambda: webbrowser.open(
            "https://github.com/NathanVaughn/msfs-mod-manager/"))
        help_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Open Issues/Suggestions", self)
        menu_action.triggered.connect(lambda: webbrowser.open(
            "https://github.com/NathanVaughn/msfs-mod-manager/issues/"))
        help_menu.addAction(menu_action)

        help_menu.addSeparator()

        menu_action = QtWidgets.QAction("Open Debug Log", self)
        menu_action.triggered.connect(lambda: os.startfile(DEBUG_LOG))
        help_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Open Config File", self)
        menu_action.triggered.connect(lambda: os.startfile(CONFIG_FILE))
        help_menu.addAction(menu_action)

        help_menu.addSeparator()

        menu_action = QtWidgets.QAction("Open Community Folder", self)
        menu_action.triggered.connect(lambda: os.startfile(
            self.main_widget.flight_sim.get_sim_mod_folder()))
        help_menu.addAction(menu_action)

        menu_action = QtWidgets.QAction("Open Mod Install Folder", self)
        menu_action.triggered.connect(
            lambda: os.startfile(files.get_mod_install_folder()))
        help_menu.addAction(menu_action)
Beispiel #55
0
def documentation():
    """
    Opens documentation of the Project
    :return: opened documentatipn readme.txt file
    """
    os.startfile('F:\\Project\\edai_sy\\readme.txt')
Beispiel #56
0
    def setup_window(self):
        """Setup main window"""
        self.setWindowTitle(self.NAME)
        self.setWindowIcon(get_icon('winpython.svg'))

        self.selector = DistributionSelector(self)
        # PyQt4 old SIGNAL: self.connect(self.selector, SIGNAL('selected_distribution(QString)'),
        # PyQt4 old SIGNAL:              self.distribution_changed)
        self.selector.selected_distribution.connect(self.distribution_changed)

        self.table = PackagesTable(self, 'install', self.NAME)
        # PyQt4 old SIGNAL:self.connect(self.table, SIGNAL('package_added()'),
        # PyQt4 old SIGNAL:             self.refresh_install_button)
        self.table.package_added.connect(self.refresh_install_button)

        # PyQt4 old SIGNAL: self.connect(self.table, SIGNAL("clicked(QModelIndex)"),
        # PyQt4 old SIGNAL:              lambda index: self.refresh_install_button())
        self.table.clicked.connect(lambda index: self.refresh_install_button())

        self.untable = PackagesTable(self, 'uninstall', self.NAME)
        # PyQt4 old SIGNAL:self.connect(self.untable, SIGNAL("clicked(QModelIndex)"),
        # PyQt4 old SIGNAL:             lambda index: self.refresh_uninstall_button())
        self.untable.clicked.connect(lambda index: self.refresh_uninstall_button())

        self.selector.set_distribution(sys.prefix)
        self.distribution_changed(sys.prefix)

        self.tabwidget = QTabWidget()
        # PyQt4 old SIGNAL:self.connect(self.tabwidget, SIGNAL('currentChanged(int)'),
        # PyQt4 old SIGNAL:             self.current_tab_changed)
        self.tabwidget.currentChanged.connect(self.current_tab_changed)

        btn_layout = self._add_table(self.table, "Install/upgrade packages",
                                     get_std_icon("ArrowDown"))
        unbtn_layout = self._add_table(self.untable, "Uninstall packages",
                                       get_std_icon("DialogResetButton"))

        central_widget = QWidget()
        vlayout = QVBoxLayout()
        vlayout.addWidget(self.selector)
        vlayout.addWidget(self.tabwidget)
        central_widget.setLayout(vlayout)
        self.setCentralWidget(central_widget)

        # Install tab
        add_action = create_action(self, "&Add packages...",
                                   icon=get_std_icon('DialogOpenButton'),
                                   triggered=self.add_packages)
        self.remove_action = create_action(self, "Remove",
                                           shortcut=keybinding('Delete'),
                                           icon=get_std_icon('TrashIcon'),
                                           triggered=self.remove_packages)
        self.remove_action.setEnabled(False)
        self.select_all_action = create_action(self, "(Un)Select all",
                                   shortcut=keybinding('SelectAll'),
                                   icon=get_std_icon('DialogYesButton'),
                                   triggered=self.table.select_all)
        self.install_action = create_action(self, "&Install packages",
                            icon=get_std_icon('DialogApplyButton'),
                            triggered=lambda: self.process_packages('install'))
        self.install_action.setEnabled(False)
        quit_action = create_action(self, "&Quit",
                                    icon=get_std_icon('DialogCloseButton'),
                                    triggered=self.close)
        packages_menu = self.menuBar().addMenu("&Packages")
        add_actions(packages_menu, [add_action, self.remove_action,
                                    self.install_action,
                                    None, quit_action])

        # Uninstall tab
        self.uninstall_action = create_action(self, "&Uninstall packages",
                       icon=get_std_icon('DialogCancelButton'),
                       triggered=lambda: self.process_packages('uninstall'))
        self.uninstall_action.setEnabled(False)

        uninstall_btn = action2button(self.uninstall_action, autoraise=False,
                                      text_beside_icon=True)

        # Option menu
        option_menu = self.menuBar().addMenu("&Options")
        repair_action = create_action(self, "Repair packages",
                      tip="Reinstall packages even if version is unchanged",
                      toggled=self.toggle_repair)
        add_actions(option_menu, (repair_action,))

        # Advanced menu
        option_menu = self.menuBar().addMenu("&Advanced")
        register_action = create_action(self, "Register distribution...",
                      tip="Register file extensions, icons and context menu",
                      triggered=self.register_distribution)
        unregister_action = create_action(self, "Unregister distribution...",
                      tip="Unregister file extensions, icons and context menu",
                      triggered=self.unregister_distribution)
        open_console_action = create_action(self, "Open console here",
                    triggered=lambda: os.startfile(self.command_prompt_path))
        open_console_action.setEnabled(osp.exists(self.command_prompt_path))
        add_actions(option_menu, (register_action, unregister_action,
                                  None, open_console_action))

        # # View menu
        # view_menu = self.menuBar().addMenu("&View")
        # popmenu = self.createPopupMenu()
        # add_actions(view_menu, popmenu.actions())

        # Help menu
        about_action = create_action(self, "About %s..." % self.NAME,
                                icon=get_std_icon('MessageBoxInformation'),
                                triggered=self.about)
        report_action = create_action(self, "Report issue...",
                                icon=get_icon('bug.png'),
                                triggered=self.report_issue)
        help_menu = self.menuBar().addMenu("?")
        add_actions(help_menu, [about_action, None, report_action])

        # Status bar
        status = self.statusBar()
        status.setObjectName("StatusBar")
        status.showMessage("Welcome to %s!" % self.NAME, 5000)

        # Button layouts
        for act in (add_action, self.remove_action, None,
                    self.select_all_action, self.install_action):
            if act is None:
                btn_layout.addStretch()
            else:
                btn_layout.addWidget(action2button(act, autoraise=False,
                                                   text_beside_icon=True))
        unbtn_layout.addWidget(uninstall_btn)
        unbtn_layout.addStretch()

        self.resize(400, 500)
Beispiel #57
0
x = 1
yol = 'dikkat.vbs'
yolo = 'dikkat2.vbs'

while x == 1:
    os.system('cls')
    print(
        "-------------------------------------------------------------------------------"
    )
    print("Dolar Kuru 	 	Saat                   Tarih")
    print(
        "-------------------------------------------------------------------------------"
    )
    url = "https://dolarrekorkirdimi.com/"
    url_oku = urllib.request.urlopen(url)
    soup = BeautifulSoup(url_oku, 'html.parser')
    ho = soup.find("h6")
    ho = ho.text
    b = "$1,Şimdi,=,₺, "
    for char in b:
        ho = str(ho).replace(char, "")
    if str(ho) > str(can):
        os.startfile(yol)
    if str(ho) < str(cano):
        os.startfile(yolo)
    baby = ho
    print(baby, "                ", zaman, "                ", tarih)
    with open('kur.txt', 'a') as f:
        f.write('\n' + baby + "                  " + zaman +
                "                  " + tarih)
    time.sleep(5)
Beispiel #58
0
def runApps():
    for app in apps:
        os.startfile(app)
Beispiel #59
0
                'Please input your password:(不会回显,输入完成<ENTER>即可) ')

        # Captcha 验证码 # Fix Issue #13 bug.
        captcha_resp = session.get(
            host + '/eams/captcha/image.action')  # Captcha 验证码图片
        img_path = os.path.join(os.getcwd(), 'captcha.jpg')
        with open(img_path, 'wb') as captcha_fp:
            captcha_fp.write(captcha_resp.content)
        try:
            # 在不同平台显示验证码
            if sys.platform.find('darwin') >= 0:
                subprocess.call(['open', img_path])
            elif sys.platform.find('linux') >= 0:
                subprocess.call(['xdg-open', img_path])
            else:
                os.startfile(img_path)
        except:
            from PIL import Image

            # captcha_img = Image.open(BytesIO(captcha_resp.content))
            captcha_img = Image.open(img_path)
            captcha_img.show()  # show the captcha
            captcha_img.close()

        # text = image_to_string(captcha_img)  # 前提是装了Tesseract-OCR,可以试试自动识别
        # print(text)
        captcha_str = input('Please input the captcha: ')
        print()  # 加个空行好看一点

        # 删除验证码图片
        if sys.platform.find('darwin') >= 0:
Beispiel #60
0
def main():

    if _north_ == None:
        north = 0.00
    else:
        north = _north_

    # name of file
    if fileName_ == None:
        fileName = 'LBenvimet.INX'
    else:
        fileName = fileName_ + '.INX'

    if not os.path.exists(_envimetFolder):
        os.makedirs(_envimetFolder)
    fileAddress = _envimetFolder + '\\' + fileName

    numX, numY, dimX, dimY, dimZ = _envimetGrid.numX + 1, _envimetGrid.numY + 1, _envimetGrid.dimX, _envimetGrid.dimY, _envimetGrid.dimZ
    numZ, verticalStretch, startStretch = _envimetGrid.zGrids, _envimetGrid.telescope, _envimetGrid.startTelescopeHeight
    telescopingGrid = 1 if _envimetGrid.telescope else 0

    # create grid
    if _envimetObjects_ or _baseSurface_:
        gridPoints = createGrid(_envimetObjects_, _baseSurface_, _envimetGrid)

        if _runIt:
            # create parts
            envimetObjDict = evimetPartsGenerator(_envimetObjects_,
                                                  _envimetGrid, gridPoints)
            # add emptyMatrix
            envimetObjDict['EmptyMatrix'] = _envimetGrid.emptyMatrix()
            # keys
            envimetObjDictKeys = envimetObjDict.keys()
            # default assignments
            terrain3d, buildingFlag, building3D, plant2d, plant3d, source, terrain2d, buildingBottom2d, buildingTop2d, buildingCommonMaterial, soil, buildingEmptyMatrix, buildingIds = '', '', '', envimetObjDict[
                'EmptyMatrix'], '', envimetObjDict[
                    'EmptyMatrix'], envimetObjDict[
                        'EmptyMatrix'], envimetObjDict[
                            'EmptyMatrix'], envimetObjDict['EmptyMatrix'], [
                                '00', '00'
                            ], re.sub(
                                '', 'LO',
                                envimetObjDict['EmptyMatrix']), re.sub(
                                    '', '0',
                                    envimetObjDict['EmptyMatrix']), re.sub(
                                        '', '0', envimetObjDict['EmptyMatrix'])

            for key in envimetObjDictKeys:
                if key == 'BuildingCommonMaterial':
                    buildingCommonMaterial = envimetObjDict[
                        'BuildingCommonMaterial']
                elif key == 'BuildingEmptyMatrix':
                    buildingEmptyMatrix = envimetObjDict['BuildingEmptyMatrix']
                elif key == 'BuildingIds':
                    buildingIds = envimetObjDict['BuildingIds']
                elif key == 'BuildingBottom2d':
                    buildingBottom2d = envimetObjDict['BuildingBottom2d']
                elif key == 'BuildingTop2d':
                    buildingTop2d = envimetObjDict['BuildingTop2d']
                elif key == 'Terrain3d':
                    terrain3d = envimetObjDict['Terrain3d']
                elif key == 'BuildingFlag':
                    buildingFlag = envimetObjDict['BuildingFlag']
                elif key == 'Building3D':
                    building3D = envimetObjDict['Building3D']
                elif key == 'Plant2d':
                    plant2d = envimetObjDict['Plant2d']
                elif key == 'Plant3d':
                    plant3d = envimetObjDict['Plant3d']
                elif key == 'Soil':
                    soil = envimetObjDict['Soil']
                elif key == 'Source':
                    source = envimetObjDict['Source']
                elif key == 'EmptyMatrix':
                    emptyMatrix = envimetObjDict['EmptyMatrix']
                elif key == 'Terrain2d':
                    terrain2d = envimetObjDict['Terrain2d']

            # other args
            isFull3DDesign = 1
            if nestingGrid_:
                numNesting = nestingGrid_.numNestingGrid
                matNesting = [
                    nestingGrid_.soilProfileA, nestingGrid_.soilProfileB
                ]
            else:
                numNesting, matNesting = 3, ['LO', 'LO']
            location = _envimetLocation.locationAttributes

            # write file
            writeINX(fileAddress,
                     numX,
                     numY,
                     numZ,
                     dimX,
                     dimY,
                     dimZ,
                     str(numNesting),
                     matNesting,
                     location,
                     north,
                     buildingCommonMaterial,
                     buildingEmptyMatrix,
                     buildingIds,
                     buildingBottom2d,
                     buildingTop2d,
                     terrain3d,
                     buildingFlag,
                     building3D,
                     plant2d,
                     plant3d,
                     soil,
                     source,
                     emptyMatrix,
                     terrain2d,
                     isFull3DDesign,
                     verticalStretch,
                     startStretch,
                     telescopingGrid,
                     has3DModel=1)

            INXfileAddress = fileAddress

            # open the file
            os.startfile(INXfileAddress)

            return gridPoints, INXfileAddress

        return gridPoints, None

    else:
        w = gh.GH_RuntimeMessageLevel.Warning
        message = "Please provide envimetBuildings if your grid is based on buildings "\
        "or baseSurface if your grid is based on surface"
        ghenv.Component.AddRuntimeMessage(w, message)
        return None, None