简短的回答是,os.system
不知道在哪里可以找到firefox.exe
。
可能的解决方案是使用完整路径。并建议使用subprocess
模块:
import subprocess
subprocess.call(['C:\Program Files\Mozilla Firefox\\firefox.exe'])
心灵的\\
的firefox.exe
之前!如果你会使用\f
,巨蟒将其解释为换页:
>>> print('C:\Program Files\Mozilla Firefox\firefox.exe')
C:\Program Files\Mozilla Firefox
irefox.exe
当然,这不存在路径和。 :-)
因此,无论转义反斜线或使用原始字符串:
>>> 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
注意,使用os.system
或subprocess.call
将停止当前的应用程序,直到启动完成程序。所以你可能想用subprocess.Popen
代替。这将启动外部程序,然后继续脚本。
subprocess.Popen(['C:\Program Files\Mozilla Firefox\\firefox.exe', '-new-tab'])
这将打开firefox(或在运行实例中创建一个新的选项卡)。
一个更完整的例子是我通过github发布的open
实用程序。这使用正则表达式来匹配文件扩展名到程序来打开这些文件。然后它使用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, 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)
使用'firefox.exe'的绝对路径。 – fsp
可能的重复[如何从python执行程序? os.system失败,由于路径中的空格](http://stackoverflow.com/questions/204017/how-do-i-execute-a-program-from-python-os-system-fails-due-to-spaces -in-path) –
记事本通常位于PATH变量下的system32文件夹中,但firefox不太可能。 – YOU