Python os.startfile() Examples

The following are code examples for showing how to use os.startfile(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: A.L.F.R.E.D-The-Humanoid   Author: AyushDhanai1419   File: wikipedia_feature.py    MIT License 7 votes vote down vote up
def get_long_summary(query):
    fl = open('alfred_window.txt','w')
    summary = ''
    try:
        wiki_list = stk(wk.summary(query))
        for i in range(0,10,1):
            summary = summary + wiki_list[i]
            write(wiki_list[i],file=fl)			#Previously : print(wiki_list[i],file=fl)
    except wk.exceptions.DisambiguationError:
        summary = 'Sorry Can\'t retrieve data from internet.'
    fl.close()
    os.startfile('alfred_window.txt')
    return summary


# This function returns a image url for a particular query passed to it 
Example 2
Project: Freya   Author: areebbeigh   File: callbacks.py    Apache License 2.0 7 votes vote down vote up
def play_music(p, l):
    """ Plays music """
    respond("playing music", prepend_positive_response=True)
    playlist = os.path.join(BASE_DIRECTORY, 'playlist.m3u')

    extensions = [
        ".mp3",
        ".m4a",
        ".ogg",
        ".flac",
    ]

    music_files = _get_all_files(preferences.get_music_dir(), extensions)

    with open(playlist, 'w') as f:
        for file in music_files:
            f.write(file + "\n")

    os.startfile(playlist) 
Example 3
Project: touchdesigner-config-with-env-vars   Author: raganmd   File: Launcher.py    MIT License 6 votes vote down vote up
def Launch(**kwargs):
    envVar          = kwargs.get('envVar')
    envVal          = kwargs.get('envVal')
    target_file     = kwargs.get('targetFile')

    os.environ[envVar]  = envVal
    os.startfile(target_file)

    msg                 = '''
STARTING - - - - - - - - - - - -
File            : {file}
Env-Variable    : {var}
Env-Value       : {val}
- - - - - - - - - - - - - - - -'''.format(  file=target_file, 
                                            var=envVar, 
                                            val=envVal)
    return msg 
Example 4
Project: cprofile_graph   Author: campos-ddc   File: __init__.py    MIT License 6 votes vote down vote up
def _view_file(path):
    '''
    Open a file using the default application.

    :param path: Path to be opened.
    :type path: str
    '''
    try:
        if sys.platform.startswith('darwin'):
            r = subprocess.call(('open', path))
            if r: raise RuntimeError('Subprocess failed to open')
        elif os.name == 'nt':
            os.startfile(path)
        elif os.name == 'posix':
            r = subprocess.call(('xdg-open', path))
            if r: raise RuntimeError('Subprocess failed to open')
    except:
        # If all fails, try to use webbrowser
        import webbrowser
        webbrowser.open(path)


#=============================================================================
# METADATA
#============================================================================= 
Example 5
Project: neurotic   Author: jpgill86   File: standalone.py    MIT License 6 votes vote down vote up
def edit_metadata(self):
        """
        Open the metadata file in an editor.
        """

        path = self.metadata_selector.file

        try:

            if platform.system() == "Windows":
                os.startfile(path)
            elif platform.system() == "Darwin":
                subprocess.Popen(["open", path])
            else:
                subprocess.Popen(["xdg-open", path])

        except FileNotFoundError as e:

            print('The metadata file was not found:', e)
            return 
Example 6
Project: neurotic   Author: jpgill86   File: standalone.py    MIT License 6 votes vote down vote up
def open_directory(self):
        """
        Open the directory of the selected dataset in Win Explorer / Mac
        Finder.
        """

        metadata = self.metadata_selector.selected_metadata
        path = metadata['data_dir']

        try:

            if platform.system() == "Windows":
                os.startfile(path)
            elif platform.system() == "Darwin":
                subprocess.Popen(["open", path])
            else:
                subprocess.Popen(["xdg-open", path])

        except FileNotFoundError as e:

            print('The directory for the selected dataset was not found ' \
                  'locally, perhaps because it does not exist yet:', e) 
Example 7
Project: tuack   Author: Mulab11   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def xopen_file(path):
	try:
		if system == 'Windows':
			os.startfile(path)
		elif system == 'Darwin':
			subprocess.call(["open", path])
		else:
			subprocess.call(["xdg-open", path])
	except Exception as e:
		log.warning(u'打开文件`%s`失败。' % path)
		log.info(e) 
Example 8
Project: pipeline   Author: liorbenhorin   File: files.py    MIT License 6 votes vote down vote up
def explore(path):
    if path:
        if os.path.exists(path):
            path = os.path.dirname(path)
            platform = os_qeury()
            if platform == "darwin":
                subprocess.Popen(['open',path])
                return True
                
            elif platform == "win32":
                os.startfile(path)
                return True
        
        log.info("File dose not exist")
        return False
        
    log.info("No file name spacified")
    return False 
Example 9
Project: pipeline   Author: liorbenhorin   File: files.py    MIT License 6 votes vote down vote up
def run(filename):
    if filename:
        if os.path.exists(filename):
            if sys.platform == "win32":
                os.startfile(filename)
                return True
            else:
                opener ="open" if sys.platform == "darwin" else "xdg-open"
                subprocess.call([opener, filename]) 
                return True 
    
        log.info("File dose not exist")
        return False
        
    log.info("No file name spacified")
    return False 
Example 10
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except WindowsError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 11
Project: pyblish-win   Author: pyblish   File: test_startfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_nonexisting(self):
        self.assertRaises(OSError, startfile, "nonexisting.vbs") 
Example 12
Project: pyblish-win   Author: pyblish   File: test_startfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_nonexisting_u(self):
        self.assertRaises(OSError, startfile, u"nonexisting.vbs") 
Example 13
Project: pyblish-win   Author: pyblish   File: test_startfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_empty(self):
        empty = path.join(path.dirname(__file__), "empty.vbs")
        startfile(empty)
        startfile(empty, "open")
        # Give the child process some time to exit before we finish.
        # Otherwise the cleanup code will not be able to delete the cwd,
        # because it is still in use.
        sleep(0.1) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_startfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_empty_u(self):
        empty = path.join(path.dirname(__file__), "empty.vbs")
        startfile(unicode(empty, "mbcs"))
        startfile(unicode(empty, "mbcs"), "open")
        sleep(0.1) 
Example 15
Project: pyblish-win   Author: pyblish   File: EditorWindow.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __extra_help_callback(self, helpfile):
        "Create a callback with the helpfile value frozen at definition time"
        def display_extra_help(helpfile=helpfile):
            if not helpfile.startswith(('www', 'http')):
                helpfile = os.path.normpath(helpfile)
            if sys.platform[:3] == 'win':
                try:
                    os.startfile(helpfile)
                except WindowsError as why:
                    tkMessageBox.showerror(title='Document Start Failure',
                        message=str(why), parent=self.text)
            else:
                webbrowser.open(helpfile)
        return display_extra_help 
Example 16
Project: A.L.F.R.E.D-The-Humanoid   Author: AyushDhanai1419   File: news_api.py    MIT License 5 votes vote down vote up
def news_writer(news_list):
    os.chdir(cwd)
    f = open('alfred_window.txt','w')
    for i in news_list:
        f.write('\n\nSource    :',i[0])	#Previously : print('\n\nSource    :',i[0],file=f)
        f.write('Title     :',i[1])	#Previously : print('Title     :',i[1],file=f)
       	f.write('Author    :',i[2])	#Previously : print('Author    :',i[2],file=f)
        f.write('Summary   :',i[3])	#Previously : print('Summary   :',i[3],file=f)
    f.close()
    os.startfile('alfred_window.txt')
    return
    
# this function takes a query as an input and returns a tuple containing subject and category which help JARVIS to decide which function to call 
Example 17
Project: A.L.F.R.E.D-The-Humanoid   Author: AyushDhanai1419   File: book_api.py    MIT License 5 votes vote down vote up
def news_writer(news_list):
    os.chdir('C:\\Users\\HP\\Desktop\\J.A.R.V.I.S')
    f = open('jarvis_window.txt','w')
    for i in news_list:
        write('\n\nSource    :',i[0],file=f)	#Previously :  print('\n\nSource    :',i[0],file=f)
        write('Title     :',i[1],file=f)	#Previously :  print('Title     :',i[1],file=f)
        write('Author    :',i[2],file=f)	#Previously :  print('Author    :',i[2],file=f)
        write('Summary   :',i[3],file=f)	#Previously :  print('Summary   :',i[3],file=f)
    f.close()
    os.startfile('jarvis_window.txt')
    return


# This takes a query as an input and extract book name from that query 
Example 18
Project: A.L.F.R.E.D-The-Humanoid   Author: AyushDhanai1419   File: wikipedia_feature.py    MIT License 5 votes vote down vote up
def get_short_summary(query):
    fl = open('alfred_window.txt','w')
    summary = ''
    try:
        wiki_list = stk(wk.summary(query))
        for i in range(0,5,1):
            summary = summary + wiki_list[i]
            write(wiki_list[i],file=fl)			#Previously : print(wiki_list[i],file=fl)	
    except wk.exceptions.DisambiguationError:
        summary = 'Sorry Can\'t retrieve data from internet.'
    fl.close()
    os.startfile('alfred_window.txt')
    return summary

# This function takes query as an input and returns a string which is the long summary of the query as an output. 
Example 19
Project: loman   Author: janushendersonassetallocation   File: computeengine.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def view(self, colors='state', cmap=None):
        d = self.to_pydot(colors=colors, cmap=cmap)
        with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as f:
            f.write(d.create_pdf())
            os.startfile(f.name) 
Example 20
Project: PYMusicPlayer   Author: wangzhenjjcn   File: Player.py    GNU General Public License v3.0 5 votes vote down vote up
def Open_Path_Cmd(self, event=None):
        #TODO, Please finish the function here!
        os.startfile(os.path.abspath(download_path))
        pass 
Example 21
Project: rtreelib   Author: sergkr   File: diagram.py    MIT License 5 votes vote down vote up
def _invoke_file(filepath):
    if platform.system() == 'Darwin':  # macOS
        subprocess.call(('open', filepath))
    elif platform.system() == 'Windows':  # Windows
        # noinspection PyUnresolvedReferences
        os.startfile(filepath)
    else:  # linux variants
        subprocess.call(('xdg-open', filepath)) 
Example 22
Project: exoduscli   Author: cthlo   File: webbrowser.py    MIT License 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except WindowsError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 23
Project: DRCOG_Urbansim   Author: apdjustino   File: path.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def startfile(self):
            os.startfile(self) 
Example 24
Project: Android-Debug-Keyboard   Author: mocobk   File: ADK.py    GNU General Public License v3.0 5 votes vote down vote up
def open_cur_dir():
    os.startfile(CUR_PATH) 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: webbrowser.py    GNU General Public License v3.0 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except OSError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True

#
# Platform support for MacOS
# 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_startfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_nonexisting(self):
        self.assertRaises(OSError, startfile, "nonexisting.vbs") 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: test_startfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_empty(self):
        # We need to make sure the child process starts in a directory
        # we're not about to delete. If we're running under -j, that
        # means the test harness provided directory isn't a safe option.
        # See http://bugs.python.org/issue15526 for more details
        with support.change_cwd(path.dirname(sys.executable)):
            empty = path.join(path.dirname(__file__), "empty.vbs")
            startfile(empty)
            startfile(empty, "open") 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: editor.py    GNU General Public License v3.0 5 votes vote down vote up
def python_docs(self, event=None):
        if sys.platform[:3] == 'win':
            try:
                os.startfile(self.help_url)
            except OSError as why:
                tkMessageBox.showerror(title='Document Start Failure',
                    message=str(why), parent=self.text)
        else:
            webbrowser.open(self.help_url)
        return "break" 
Example 29
Project: NiujiaoDebugger   Author: MrSrc   File: editor.py    GNU General Public License v3.0 5 votes vote down vote up
def __extra_help_callback(self, helpfile):
        "Create a callback with the helpfile value frozen at definition time"
        def display_extra_help(helpfile=helpfile):
            if not helpfile.startswith(('www', 'http')):
                helpfile = os.path.normpath(helpfile)
            if sys.platform[:3] == 'win':
                try:
                    os.startfile(helpfile)
                except OSError as why:
                    tkMessageBox.showerror(title='Document Start Failure',
                        message=str(why), parent=self.text)
            else:
                webbrowser.open(helpfile)
        return display_extra_help 
Example 30
Project: cassandra-migrate   Author: Cobliteam   File: cli.py    MIT License 5 votes vote down vote up
def open_file(filename):
    if sys.platform == 'win32':
        os.startfile(filename)
    else:
        if 'XDG_CURRENT_DESKTOP' in os.environ:
            opener = ['xdg-open']
        elif 'EDITOR' in os.environ:
            opener = [os.environ['EDITOR']]
        else:
            opener = ['vi']

        opener.append(filename)
        subprocess.call(opener) 
Example 31
Project: gradefast   Author: jhartz   File: hosts.py    MIT License 5 votes vote down vote up
def open_folder(self, path: Path) -> None:
        local_path_str = self.gradefast_path_to_local_path(path).get_local_path()
        self.logger.debug("Using startfile to open folder at {}", local_path_str)
        os.startfile(local_path_str) 
Example 32
Project: sql-editor   Author: struts2spring   File: BookThumbCrtl.py    MIT License 5 votes vote down vote up
def openFolderPath(self, event):
        logger.debug("OnOpenFolderPath %s", self._selected)
        if self._selected != None:
            book = self._items[self._selected].book
            file = book.bookPath
        if sys.platform == 'linux2':
            subprocess.call(["xdg-open", file])
        elif sys.platform == 'win32':
            os.startfile(file) 
Example 33
Project: sql-editor   Author: struts2spring   File: BookThumbCrtl.py    MIT License 5 votes vote down vote up
def openBook(self, event):
        logger.debug('_selected : %s', self._selected)
        if self._selected != None:
            book = self._items[self._selected].book
            logger.debug(self._selected)
            bookPath = book.bookPath
            file = os.path.join(bookPath, book.bookFileName)
#             for name in os.listdir(bookPath):
#                 if book.bookFormat != None:
#                     if "." + (book.bookFormat).lower() in name:
#                         file = os.path.join(bookPath, name)
#                         break

            if platform.system() == 'Linux':
                if book.bookFormat != None and  book.bookFormat.lower() != 'cbr':
                    try:
                        subprocess.call(["xdg-open", file])
                    except Exception as e:
                        logger.error(e, exc_info=True)
#                         logger.info('unable to open file')
                else:
#                     frame = CbrFrame(None, book)
                    pass
            elif platform.system() == 'Windows':
                os.startfile(file)
        logger.debug("openBook \n") 
Example 34
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: bCNC.py    MIT License 5 votes vote down vote up
def showUserFile(self):
		webbrowser.open(Utils.iniUser)
		#os.startfile(Utils.iniUser)

	#----------------------------------------------------------------------- 
Example 35
Project: PDF_Merge_and_Edit   Author: simonwongwong   File: PDF_Merge_and_Edit.py    MIT License 5 votes vote down vote up
def finished(file, operation, window):
    finishPrompt = tk.Tk()
    finishPrompt.title(operation + " completed!")
    tk.Label(finishPrompt, text=operation + " finished. Would you like to open the file now?").grid(row=0, column=0, columnspan=2, pady=5, padx=5)
    tk.Button(finishPrompt, text="Open file", command=lambda: os.startfile(file)).grid(row=1, column=0, pady=5, padx=5, sticky=stickyFill)
    tk.Button(finishPrompt, text="Finished", command=lambda: finishPrompt.destroy()).grid(row=1, column=1, pady=5, padx=5, sticky=stickyFill)
    finishPrompt.mainloop() 
Example 36
Project: momo   Author: shichao-an   File: utils.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def open_default(path):
    if platform.system() == 'Darwin':
        sh.open(path)
    elif os.name == 'nt':
        os.startfile(path)
    elif os.name == 'posix':
        run = sh.Command('xdg-open')
        run(path) 
Example 37
Project: pysagec   Author: migonzalvar   File: test_functional.py    MIT License 5 votes vote down vote up
def launch(filename):
    if sys.platform == "win32":
        os.startfile(filename)
    else:
        opener = "open" if sys.platform == "darwin" else "xdg-open"
        subprocess.call([opener, filename]) 
Example 38
Project: interview-with-python   Author: thundergolfer   File: exercise_launcher.py    MIT License 5 votes vote down vote up
def launch_python_script( filepath ):
    """ Launch an editor for the named python script. """

    import subprocess, os
    if sys.platform.startswith('darwin'):
        subprocess.call(('open', filepath))
    elif os.name == 'nt':
        os.startfile(filepath)
    elif os.name == 'posix':
        subprocess.call(('xdg-open', filepath)) 
Example 39
Project: railworks-dispatcher   Author: piotrkilczuk   File: dispatcher.py    MIT License 5 votes vote down vote up
def launch_html(path):
    try:
        os.startfile(path)
    except AttributeError:
        os.system('xdg-open \'%s\'' % path)


# @TODO: put this in a class 
Example 40
Project: NS3-IoT-Simulator   Author: sapgan   File: show_dependencies.py    GNU General Public License v2.0 5 votes vote down vote up
def openfile(f):
    if sys.platform.startswith('linux'):
        subprocess.call(["xdg-open", f])
    else:
        os.startfile(f) 
Example 41
Project: eddy   Author: obdasystems   File: path.py    GNU General Public License v3.0 5 votes vote down vote up
def openPath(path):
    """
    Open the given path using the OS default program.
    :type path: str
    """
    path = expandPath(path)
    if os.path.isfile(path) or os.path.isdir(path):
        if __WIN32:
            os.startfile(path)
        elif __MACOS:
            os.system('open "{0}"'.format(path))
        elif __LINUX:
            os.system('xdg-open "{0}"'.format(path)) 
Example 42
Project: whoip   Author: aaronsdevera   File: whoip.py    MIT License 5 votes vote down vote up
def genmap(filepath):
    if sys.platform=='win32':
        os.startfile(filepath)
    elif sys.platform=='darwin':
        print 'Map file saved as ' + filepath
        subprocess.Popen(['open',filepath])
    else:
        try:
            subprocess.Popen(['xdg-open', filepath])
        except OSError:
            print 'Please open a browser on: ' + filepath 
Example 43
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def _edit(self, *ignore):
        os.startfile(self.Module.file) 
Example 44
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def _show(self, *_):
        dirname = os.path.dirname(self.Module.file)
        os.startfile(dirname) 
Example 45
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def elevate(argv=None, cwd=None, use_arguments=True, show=True):
    """Run a subprocess with elevated privileges.

    (Should work with both UAC and Guest accounts)

    @param argv: Command to run. C{None} for self.
    @param cwd: Working directory or C{None} for C{os.getcwd()}
    @param use_arguments: If False, PyWin32 is not required.
    @param show: See bShow in C{win32api.ShellExecute} docs.
                        (Ignored if use_arguments = C{False})

    @note: This assumes that sys.argv[0] is absolute or relative to cwd.
    @todo: Get access to something newer than XP to test on.
    """
    argv = argv or sys.argv
    cwd = cwd or os.getcwd()

    if isinstance(argv, basestring):
        argv = [argv]
    cmd = os.path.normpath(argv[0])

    if use_arguments:
        from win32api import ShellExecute
        from subprocess import list2cmdline

        args = list2cmdline(argv[1:])
        ShellExecute(0, 'runas', cmd, args, cwd, show)
    else:
        os.chdir(cwd)
        os.startfile(os.path.normpath(cmd), 'runas') 
Example 46
Project: VICREO-Listener   Author: JeffreyDavidsz   File: VICREO_Listener_Windows.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def openFile(path):
	os.startfile(path)

#systray functions 
Example 47
Project: ironpython2   Author: IronLanguages   File: webbrowser.py    Apache License 2.0 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except WindowsError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 48
Project: ironpython2   Author: IronLanguages   File: test_startfile.py    Apache License 2.0 5 votes vote down vote up
def test_nonexisting(self):
        self.assertRaises(OSError, startfile, "nonexisting.vbs") 
Example 49
Project: ironpython2   Author: IronLanguages   File: test_startfile.py    Apache License 2.0 5 votes vote down vote up
def test_nonexisting_u(self):
        self.assertRaises(OSError, startfile, u"nonexisting.vbs") 
Example 50
Project: ironpython2   Author: IronLanguages   File: test_startfile.py    Apache License 2.0 5 votes vote down vote up
def check_empty(self, empty):
        # We need to make sure the child process starts in a directory
        # we're not about to delete. If we're running under -j, that
        # means the test harness provided directory isn't a safe option.
        # See http://bugs.python.org/issue15526 for more details
        with test_support.change_cwd(path.dirname(sys.executable)):
            startfile(empty)
            startfile(empty, "open") 
Example 51
Project: ironpython2   Author: IronLanguages   File: test_regressions.py    Apache License 2.0 5 votes vote down vote up
def test_ipy2_gh25(self):
        """https://github.com/IronLanguages/ironpython2/issues/25"""

        # this is not available on Linux systems
        if is_posix:
            self.assertRaises(AttributeError, lambda: os.startfile('/bin/bash'))
        else:
            self.assertTrue(hasattr(os, 'startfile')) 
Example 52
Project: web   Author: pythoncanarias   File: invoice_maker.py    MIT License 5 votes vote down vote up
def _open_file(filename):
        if sys.platform == "win32":
            os.startfile(filename)
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, filename]) 
Example 53
Project: PCRT   Author: sherlly   File: PCRT.py    GNU General Public License v3.0 5 votes vote down vote up
def CheckIEND(self,data):
		# IEND:length=0(4 bytes)+chunk_type='IEND'(4 bytes)+crc=AE426082(4 bytes)
		standard_IEND='\x00\x00\x00\x00IEND\xae\x42\x60\x82'
		pos=data.find('IEND')
		if pos == -1:
			print Termcolor('Detected','Lost IEND chunk! Try auto fixing...')
			IEND=standard_IEND
			print '[Finished] Now IEND chunk:%s'%(str2hex(IEND))
		else:
			IEND=data[pos-4:pos+8]
			if IEND != standard_IEND:
				print Termcolor('Detected','Error IEND chunk! Try auto fixing...')
				IEND=standard_IEND
				print '[Finished] Now IEND chunk:%s'%(str2hex(IEND))
			else:
				print '[Finished] Correct IEND chunk'
			if data[pos+8:] != '':
				print Termcolor('Detected','Some data (length: %d) append in the end (%s)'%(len(data[pos+8:]),data[pos+8:pos+18]))
				while True:
					msg = Termcolor('Notice','Try extracting them in: <1>File <2>Terminal <3>Quit [default:3] ')
					choice=raw_input(msg)
					if choice == '1':
						filename = raw_input('[File] Input the file name: ')
						file=WriteFile(filename)
						file.write(data[pos+8:])
						print '[Finished] Successfully write in %s'%(filename)
						os.startfile(os.getcwd())
					elif choice == '2':
						print 'data:',data[pos+8:]
						print 'hex(data):',data[pos+8:].encode('hex')
					elif choice == '3' or choice == '':
						break
					else:
						print Termcolor('Error','Illegal choice. Try again.')

		self.file.write(IEND)
		print '[Finished] IEND chunk check complete'
		return 0 
Example 54
Project: esst   Author: theendsofinvention   File: _ur_voice_service.py    MIT License 5 votes vote down vote up
def start_service():
        """
        Starts UR voice service
        """
        exe_path = Path(FS.ur_install_path, PROC_NAME)
        if not exe_path.exists():
            raise FileNotFoundError(exe_path)
        LOGGER.info('starting UR voice service: %s', exe_path)
        os.startfile(str(exe_path))  # nosec
        URVoiceService.is_running() 
Example 55
Project: auto_py_torrent   Author: ocslegna   File: auto_py_torrent.py    MIT License 5 votes vote down vote up
def open_magnet(self):
        """Open magnet according to os."""
        if sys.platform.startswith('linux'):
            subprocess.Popen(['xdg-open', self.magnet],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        elif sys.platform.startswith('win32'):
            os.startfile(self.magnet)
        elif sys.platform.startswith('cygwin'):
            os.startfile(self.magnet)
        elif sys.platform.startswith('darwin'):
            subprocess.Popen(['open', self.magnet],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        else:
            subprocess.Popen(['xdg-open', self.magnet],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
Example 56
Project: FestEngine   Author: Himura2la   File: settings.py    GNU General Public License v3.0 5 votes vote down vote up
def on_file_edit(self, e=None):
        config_path = self.session_picker.GetPath()

        if sys.platform.startswith('linux'):  # for Linux using the X Server
            subprocess.call(('xdg-open', config_path))
        elif sys.platform == "win32":  # for Windows
            os.startfile(config_path)
        elif sys.platform == "darwin":  # for MacOS
            subprocess.call(('open', config_path))

        with wx.MessageDialog(self, _("The operating system is opening the '%s' file.\n"
                                      "It is in JSON format, use any plain-text editor to open it.\n"
                                      "For instance: AkelPad, Visual Studio Code, Notepad, etc.\n\n"
                                      "Edit the file very carefully and save it.\n"
                                      "Then hit 'OK' to load the new config or 'Cancel' to revert your changes.") %
                                              os.path.basename(config_path),
                              _("Manual Configuration"), wx.OK | wx.CANCEL | wx.ICON_INFORMATION) as restart_dialog:
            action = restart_dialog.ShowModal()
            if action == wx.ID_OK:
                try:
                    self.config = json.load(open(config_path, 'r', encoding='utf-8-sig'))
                    self.EndModal(wx.ID_OPEN)
                except json.decoder.JSONDecodeError as e:
                    msg = _("Unfortunately, you broke the JSON format...\n"
                            "Please fix the configuration file%s ASAP.\n\nDetails: %s") % ("", str(e))
                    wx.MessageBox(msg, "JSON Error", wx.OK | wx.ICON_ERROR, self)
            elif action == wx.ID_CANCEL:
                json.dump(self.config, open(config_path, 'w', encoding='utf-8'),
                          ensure_ascii=False, indent=4)
                self.EndModal(wx.ID_CANCEL) 
Example 57
Project: Eyecandy-py   Author: Alquimista   File: helpers.py    MIT License 5 votes vote down vote up
def start_file(filename):
    if os.name == 'mac':
        subprocess.call(('open', filename))
    elif os.name == 'nt':
        os.startfile(filename)
    elif os.name == 'posix':
        subprocess.call(('xdg-open', filename)) 
Example 58
Project: Blockly-rduino-communication   Author: technologiescollege   File: idlexManager.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, text):
        if sys.platform[:3] == 'win':
            try:
                os.startfile(UPDATE_URL)
            except WindowsError as why:
                tkMessageBox.showerror(title='Unable to load IdleX update page.',
                    message=str(why), parent=text)
        else:
            webbrowser.open(UPDATE_URL) 
Example 59
Project: Blockly-rduino-communication   Author: technologiescollege   File: webbrowser.py    GNU General Public License v3.0 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except OSError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 60
Project: program.plexus   Author: tvaddonsco   File: acecore.py    GNU General Public License v2.0 5 votes vote down vote up
def startWin(self):
        try:
            needed_value='ace_engine.exe'
            path_value=os.path.join(pastaperfil,'acestream',needed_value)
            self.log.out("Try to start %s"%needed_value)
            self.progress.update(0,'Starting ASEngine','')
            os.startfile(path_value)
            self.log.out('AceStream Engine starting')
        except:
            self.sm('Not Installed')
            self.log.out('Not Installed')
            self.progress.update(0,'AceStream not installed','')
            return False
        return True 
Example 61
Project: PyCreator   Author: Zachacious   File: fileBrowser.py    MIT License 5 votes vote down vote up
def execFile(self):
        """execFile() -- execute the selected file in the browser."""
        if self.tree_view is not None:  # FileSystemContextMenu.tree_view
            urls = self.tree_view.helper.selected_urls()
            # execute all selected
            for u in urls:
                if os.path.isfile(u):
                    os.startfile(u)

# ===-------------------------------------=== 
Example 62
Project: artellalauncher   Author: tpoveda   File: config.py    MIT License 5 votes vote down vote up
def edit(self):
        """
        Edit file with default OS application
        """

        if platform.system().lower() == 'windows':
            os.startfile(str(self.config_file))
        else:
            if platform.system().lower() == 'darwin':
                call = 'open'
            else:
                call = 'xdg-open'
            subprocess.call(call, self.config_file) 
Example 63
Project: IronHydra   Author: microdee   File: webbrowser.py    MIT License 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except WindowsError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 64
Project: boneca   Author: ffreitasalves   File: boneca.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def handle_win_f3 ():
    os.startfile(os.path.join(os.path.realpath(os.path.dirname(sys.argv[0])),"seu-boneco.jpg")) 
Example 65
Project: Nuke-WrapItUp   Author: max-van-leeuwen   File: WrapItUp.py    MIT License 5 votes vote down vote up
def OpenFolder(folderPath = ''):

		if folderPath == '':
			folderPath = WCurrItemPath.toolTip()
		oFolderPath = folderPath

		try:
			# get parent dir
			if not os.path.isdir(folderPath):
				folderPath = os.path.dirname(folderPath)

			# get project directory folder
			if not os.path.isdir(folderPath):
				folderPath = ProjectDirectory(oFolderPath)


			if os.path.isdir(folderPath):

				if sys.platform == 'win32':
					folderPath = folderPath.replace('/', '\\')
					os.startfile(folderPath)
				else:
					opener ="open" if sys.platform == "darwin" else "xdg-open"
					subprocess.call([opener, folderPath])


			else:
				print folderPath

		except Exception, e:
			pass 
Example 66
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: webbrowser.py    GNU General Public License v2.0 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except OSError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True

#
# Platform support for MacOS
# 
Example 67
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_startfile.py    GNU General Public License v2.0 5 votes vote down vote up
def test_nonexisting(self):
        self.assertRaises(OSError, startfile, "nonexisting.vbs") 
Example 68
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_startfile.py    GNU General Public License v2.0 5 votes vote down vote up
def test_empty(self):
        # We need to make sure the child process starts in a directory
        # we're not about to delete. If we're running under -j, that
        # means the test harness provided directory isn't a safe option.
        # See http://bugs.python.org/issue15526 for more details
        with support.change_cwd(path.dirname(sys.executable)):
            empty = path.join(path.dirname(__file__), "empty.vbs")
            startfile(empty)
            startfile(empty, "open") 
Example 69
Project: aws-lambda-runtime-pypy   Author: uscheller   File: webbrowser.py    Apache License 2.0 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except OSError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 70
Project: aws-lambda-runtime-pypy   Author: uscheller   File: EditorWindow.py    Apache License 2.0 5 votes vote down vote up
def python_docs(self, event=None):
        if sys.platform[:3] == 'win':
            try:
                os.startfile(self.help_url)
            except OSError as why:
                tkMessageBox.showerror(title='Document Start Failure',
                    message=str(why), parent=self.text)
        else:
            webbrowser.open(self.help_url)
        return "break" 
Example 71
Project: aws-lambda-runtime-pypy   Author: uscheller   File: EditorWindow.py    Apache License 2.0 5 votes vote down vote up
def __extra_help_callback(self, helpfile):
        "Create a callback with the helpfile value frozen at definition time"
        def display_extra_help(helpfile=helpfile):
            if not helpfile.startswith(('www', 'http')):
                helpfile = os.path.normpath(helpfile)
            if sys.platform[:3] == 'win':
                try:
                    os.startfile(helpfile)
                except OSError as why:
                    tkMessageBox.showerror(title='Document Start Failure',
                        message=str(why), parent=self.text)
            else:
                webbrowser.open(helpfile)
        return display_extra_help 
Example 72
Project: biweeklybudget   Author: jantman   File: cli.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def open_with_ofx_handler(filename):
    import platform
    sysname = platform.system()
    if sysname == 'Darwin':
        os.system("/usr/bin/open '%s'" % filename)
    elif sysname == 'Windows':
        os.startfile(filename)
    else:
        # linux
        os.system("xdg-open '%s'" % filename) 
Example 73
Project: PyBER   Author: aff3ct   File: fileExplorer.py    MIT License 5 votes vote down vote up
def openFileOrDir(self, *args):
		paths = [ self.model().filePath(index) for index in args ]
		if len(paths):
			if sys.platform == "linux" or sys.platform == "linux2":
				subprocess.call(["xdg-open", paths[0]])
			elif sys.platform == "darwin":
				subprocess.call(["open", paths[0]])
			else:
				os.startfile(paths[0]) 
Example 74
Project: Computable   Author: ktraunmueller   File: _path.py    MIT License 5 votes vote down vote up
def startfile(self):
            os.startfile(self) 
Example 75
Project: pipeline   Author: liorbenhorin   File: email.py    MIT License 5 votes vote down vote up
def open(self, filename):
            try:
                os.startfile(filename)
            except WindowsError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 76
Project: sina_fund_crawler   Author: terryding77   File: gui.py    Apache License 2.0 5 votes vote down vote up
def open():
        print('Open folder ./')
        os.startfile(os.path.abspath('./')) 
Example 77
Project: oss-ftp   Author: aliyun   File: webbrowser.py    MIT License 5 votes vote down vote up
def open(self, url, new=0, autoraise=True):
            try:
                os.startfile(url)
            except WindowsError:
                # [Error 22] No application is associated with the specified
                # file for this operation: '<URL>'
                return False
            else:
                return True 
Example 78
Project: oss-ftp   Author: aliyun   File: test_startfile.py    MIT License 5 votes vote down vote up
def test_nonexisting(self):
        self.assertRaises(OSError, startfile, "nonexisting.vbs") 
Example 79
Project: oss-ftp   Author: aliyun   File: test_startfile.py    MIT License 5 votes vote down vote up
def test_nonexisting_u(self):
        self.assertRaises(OSError, startfile, u"nonexisting.vbs") 
Example 80
Project: CyberScan   Author: medbenali   File: utils.py    GNU General Public License v3.0 4 votes vote down vote up
def do_graph(graph,prog=None,format=None,target=None,type=None,string=None,options=None):
    """do_graph(graph, prog=conf.prog.dot, format="svg",
         target="| conf.prog.display", options=None, [string=1]):
    string: if not None, simply return the graph string
    graph: GraphViz graph description
    format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option
    target: filename or redirect. Defaults pipe to Imagemagick's display program
    prog: which graphviz program to use
    options: options to be passed to prog"""
        
    if format is None:
        if WINDOWS:
            format = "png" # use common format to make sure a viewer is installed
        else:
            format = "svg"
    if string:
        return graph
    if type is not None:
        format=type
    if prog is None:
        prog = conf.prog.dot
    start_viewer=False
    if target is None:
        if WINDOWS:
            tempfile = os.tempnam("", "scapy") + "." + format
            target = "> %s" % tempfile
            start_viewer = True
        else:
            target = "| %s" % conf.prog.display
    if format is not None:
        format = "-T %s" % format
    w,r = os.popen2("%s %s %s %s" % (prog,options or "", format or "", target))
    w.write(graph)
    w.close()
    if start_viewer:
        # Workaround for file not found error: We wait until tempfile is written.
        waiting_start = time.time()
        while not os.path.exists(tempfile):
            time.sleep(0.1)
            if time.time() - waiting_start > 3:
                warning("Temporary file '%s' could not be written. Graphic will not be displayed." % tempfile)
                break
        else:  
            if conf.prog.display == conf.prog._default:
                os.startfile(tempfile)
            else:
                subprocess.Popen([conf.prog.display, tempfile])