如何在Python中打开外部程序

如何在Python中打开外部程序,第1张

如何在Python中打开外部程序

简短的答案是

os.system
不知道在哪里找到
firefox.exe

一种可能的解决方案是使用完整路径。并且建议使用该

subprocess
模块:

import subprocesssubprocess.call(['C:Program FilesMozilla Firefox\firefox.exe'])

注意

\
之前
firefox.exe
!如果您使用
f
,Python会将其解释为换页:

>>> print('C:Program FilesMozilla Firefoxfirefox.exe')C:Program FilesMozilla Firefox          irefox.exe

当然,这条道路是不存在的。:-)

因此,请转义反斜杠或使用原始字符串:

>>> print('C:Program FilesMozilla Firefox\firefox.exe')C:Program FilesMozilla Firefoxfirefox.exe>>> print(r'C:Program FilesMozilla Firefoxfirefox.exe')C:Program FilesMozilla Firefoxfirefox.exe

请注意,使用

os.system
subprocess.call
将停止当前应用程序,直到启动的程序完成。因此,您可能想使用它
subprocess.Popen
。这将启动外部程序,然后继续执行脚本。

subprocess.Popen(['C:Program FilesMozilla Firefox\firefox.exe', '-new-tab'])

这将打开Firefox(或在运行的实例中创建一个新选项卡)。


一个更完整的示例是我

open
通过github发布的实用程序。这使用正则表达式将文件扩展名与打开这些文件的程序进行匹配。然后使用它
subprocess.Popen
在适当的程序中打开那些文件。作为参考,我在下面添加了当前版本的完整代码。

请注意,该程序是在考虑类似UNIX的 *** 作系统的情况下编写的。在ms-windows上,您可能会从注册表中获取文件类型的应用程序。

"""Opens the file(s) given on the command line in the appropriate program.Some of the programs are X11 programs."""from os.path import isdir, isfilefrom re import search, IGNORECASEfrom subprocess import Popen, check_output, CalledProcessErrorfrom sys import argvimport argparseimport logging__version__ = '1.3.0'# You should adjust the programs called to suit your preferences.filetypes = {    '.(pdf|epub)$': ['mupdf'],    '.html$': ['chrome', '--incognito'],    '.xcf$': ['gimp'],    '.e?ps$': ['gv'],    '.(jpe?g|png|gif|tiff?|p[abgp]m|svg)$': ['gpicview'],    '.(pax|cpio|zip|jar|ar|xar|rpm|7z)$': ['tar', 'tf'],    '.(tar.|t)(z|gz|bz2?|xz)$': ['tar', 'tf'],    '.(mp4|mkv|avi|flv|mpg|movi?|m4v|webm)$': ['mpv']}othertypes = {'dir': ['rox'], 'txt': ['gvim', '--nofork']}def main(argv):    """Entry point for this script.    Arguments:        argv: command line arguments; list of strings.    """    if argv[0].endswith(('open', 'open.py')):        del argv[0]    opts = argparse.ArgumentParser(prog='open', description=__doc__)    opts.add_argument('-v', '--version', action='version',version=__version__)    opts.add_argument('-a', '--application', help='application to use')    opts.add_argument('--log', default='warning',choices=['debug', 'info', 'warning', 'error'],help="logging level (defaults to 'warning')")    opts.add_argument("files", metavar='file', nargs='*',help="one or more files to process")    args = opts.parse_args(argv)    logging.basicConfig(level=getattr(logging, args.log.upper(), None),  format='%(levelname)s: %(message)s')    logging.info('command line arguments = {}'.format(argv))    logging.info('parsed arguments = {}'.format(args))    fail = "opening '{}' failed: {}"    for nm in args.files:        logging.info("Trying '{}'".format(nm))        if not args.application: if isdir(nm):     cmds = othertypes['dir'] + [nm] elif isfile(nm):     cmds = matchfile(filetypes, othertypes, nm) else:     cmds = None        else: cmds = [args.application, nm]        if not cmds: logging.warning("do not know how to open '{}'".format(nm)) continue        try: Popen(cmds)        except OSError as e: logging.error(fail.format(nm, e))    else:  # No files named        if args.application: try:     Popen([args.application]) except OSError as e:     logging.error(fail.format(args.application, e))def matchfile(fdict, odict, fname):    """For the given filename, returns the matching program. It uses the `file`    utility commonly available on UNIX.    Arguments:        fdict: Handlers for files. A dictionary of regex:(commands) representing the file type and the action that is to be taken for opening one.        odict: Handlers for other types. A dictionary of str:(arguments).        fname: A string containing the name of the file to be opened.    Returns: A list of commands for subprocess.Popen.    """    for k, v in fdict.items():        if search(k, fname, IGNORECASE) is not None: return v + [fname]    try:        if b'text' in check_output(['file', fname]): return odict['txt'] + [fname]    except CalledProcessError:        logging.warning("the command 'file {}' failed.".format(fname))        return Noneif __name__ == '__main__':    main(argv)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5617000.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存