如何在Python中打开外部程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37238645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:06:53  来源:igfitidea点击:

How to open external programs in Python

pythonbotslaunch

提问by Lightningblizerd

Duplicate edit: no, i did that but it doesnt want to launch firefox. I am making a cortana/siri assistant thing, and I want it to lets say open a web browser when I say something. So I have done the if part, but I just need it to launch firefox.exe I have tried different things and I get an error . Here is the code. Please help! It works with opening notepad but not firefox..

重复编辑:不,我这样做了,但它不想启动 Firefox。我正在制作一个 Cortana/siri 助手,我希望它可以在我说话时打开一个网络浏览器。所以我已经完成了 if 部分,但我只需要它来启动 firefox.exe 我尝试了不同的事情,但出现错误。这是代码。请帮忙!它适用于打开记事本,但不适用于 Firefox ..

#subprocess.Popen(['C:\Program Files\Mozilla Firefox\firefox.exe']) opens the app and continues the script
#subprocess.call(['C:\Program Files\Mozilla Firefox\firefox.exe']) this opens it but doesnt continue the script

import os
import subprocess

print "Hello, I am Danbot.. If you are new ask for help!" #intro

prompt = ">"     #sets the bit that indicates to input to >

input = raw_input (prompt)      #sets whatever you say to the input so bot can proces

raw_input (prompt)     #makes an input


if input == "help": #if the input is that
 print "*****************************************************************" #says that
 print "I am only being created.. more feautrues coming soon!" #says that
 print "*****************************************************************" #says that
 print "What is your name talks about names" #says that
 print "Open (name of program) opens an application" #says that
 print "sometimes a command is ignored.. restart me then!"
 print "Also, once you type in a command, press enter a couple of times.."
 print "*****************************************************************" #says that

raw_input (prompt)     #makes an input

if input == "open notepad": #if the input is that
 print "opening notepad!!" #says that
 print os.system('notepad.exe') #starts notepad

if input == "open the internet": #if the input is that
 print "opening firefox!!" #says that
 subprocess.Popen(['C:\Program Files\Mozilla Firefox\firefox.exe'])

回答by Roland Smith

The short answer is that os.systemdoesn't know where to find firefox.exe.

简短的回答是os.system不知道在哪里可以找到firefox.exe

A possible solution would be to use the full path. And it is recommended to use the subprocessmodule:

一个可能的解决方案是使用完整路径。并且推荐使用subprocess模块:

import subprocess

subprocess.call(['C:\Program Files\Mozilla Firefox\firefox.exe'])

Mind the \\before the firefox.exe! If you'd use \f, Python would interpret this as a formfeed:

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

>>> print('C:\Program Files\Mozilla Firefox\firefox.exe')
C:\Program Files\Mozilla Firefox
                                irefox.exe

And of course that path doesn't exist. :-)

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

So either escape the backslash or use a raw string:

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

>>> print('C:\Program Files\Mozilla Firefox\firefox.exe')
C:\Program Files\Mozilla Firefox\firefox.exe
>>> print(r'C:\Program Files\Mozilla Firefox\firefox.exe')
C:\Program Files\Mozilla Firefox\firefox.exe

Note that using os.systemor subprocess.callwill stop the current application until the program that is started finishes. So you might want to use subprocess.Popeninstead. That will launch the external program and then continue the script.

请注意,使用os.systemsubprocess.call将停止当前应用程序,直到启动的程序完成。所以你可能想subprocess.Popen改用。这将启动外部程序,然后继续脚本。

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

This will open firefox (or create a new tab in a running instance).

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



A more complete example is my openutility I publish via github. This uses regular expressions to match file extensions to programs to open those files with. Then it uses subprocess.Popento open those files in an appropriate program. For reference I'm adding the complete code for the current version below.

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

Note that this program was written with UNIX-like operating systems in mind. On ms-windows you could probably get an application for a filetype from the registry.

请注意,此程序是为类 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, isfile
from re import search, IGNORECASE
from subprocess import Popen, check_output, CalledProcessError
from sys import argv
import argparse
import 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 None


if __name__ == '__main__':
    main(argv)