7

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..

#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'])
Lightningblizerd
  • 103
  • 1
  • 2
  • 9
  • 3
    Use the absolute path to `firefox.exe`. – fsp May 15 '16 at 13:06
  • Possible duplicate of [How do I execute a program from python? os.system fails due to spaces in path](http://stackoverflow.com/questions/204017/how-do-i-execute-a-program-from-python-os-system-fails-due-to-spaces-in-path) – Valentin Lorentz May 15 '16 at 13:11
  • 1
    notepad is normally in system32 folder which is under PATH variable, but firefox is unlikely. – YOU May 15 '16 at 13:12
  • user3549596 What do you mean? this is the path: C:\Program Files\Mozilla Firefox\firefox.exe – Lightningblizerd May 15 '16 at 14:39
  • The environment variable PATH doesn't contain firefox.exe. Look into adding firefox to the environment variable PATH: http://stackoverflow.com/questions/9546324/adding-directory-to-path-environment-variable-in-windows – kanghj91 May 15 '16 at 14:41
  • That does not explain it to me.. – Lightningblizerd May 15 '16 at 15:17
  • There's much more code in this question than the bare minimum necessary to ask an unambiguous question (and, indeed, this is anything but unambiguous). See http://stackoverflow.com/help/mcve – Charles Duffy May 15 '16 at 16:56
  • 1
    ...at a minimum, show the actual error! Is it simply silently failing to open a browser window? Is it throwing an exception? Which exception? Etc, etc. There's no call at all for showing code around input-handling if your bug doesn't have anything to do with that handling; take those parts out. – Charles Duffy May 15 '16 at 16:58
  • @Charles Duffy I did. – Lightningblizerd May 18 '16 at 17:33

2 Answers2

21

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

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

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:

>>> 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.system or subprocess.call will stop the current application until the program that is started finishes. So you might want to use subprocess.Popen instead. That will launch the external program and then continue the script.

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

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


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

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.

"""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)
Roland Smith
  • 35,972
  • 3
  • 52
  • 79
  • (I also copied the exact path of my firefox location) Ok, so I did exactly the subprocces code, and when I try to launch firefox from it, it says:Traceback (most recent call last): File "Danbot.py", line 33, in subprocess.Popen(['C:\Program Files\Mozilla Firefox\firefox.exe']) File "c:\hp\bin\python\lib\subprocess.py", line 593, in __init__ errread, errwrite) File "c:\hp\bin\python\lib\subprocess.py", line 793, in _execute_child startupinfo) WindowsError: [Error 22] The filename, directory name, or volume label syntax is incorrect – Lightningblizerd May 17 '16 at 15:08
  • @Dan At a guess, that is probably because the '\f' is interpreted by Python as an escape sequence for a formfeed. Change `\f` to `\\f`. – Roland Smith May 17 '16 at 19:50
  • What \f ? I did not use anything with \f.. ? – Lightningblizerd May 18 '16 at 14:53
  • Oh, @ the firefox directory?? – Lightningblizerd May 18 '16 at 17:31
  • 1
    Yes. When Python reads `'C:\Program Files\Mozilla Firefox\firefox.exe'` it interprets the `\f` and replaces it with a formfeed character. So you get `C:\Program Files\Mozilla Firefoxirefox.exe'`, which of course doesn't exist. :-) – Roland Smith May 19 '16 at 22:44
  • You can also use package _webbrowser_ by `import webbrowser` to open the default browser. – Pranithan T. Jun 18 '19 at 04:53
  • 1
    You need double slashes `\\` on all of them, not just the last one... – birgersp Apr 17 '20 at 13:17
0

If you want to open Google or something on the web just import webbrowser and open the URL. I will give you a quick example.

import webbrowser

webbrowser.open("www.google.com")
Tomerikoo
  • 12,112
  • 9
  • 27
  • 37
  • 2
    The question is not about open something on the web (Firefox is just an example) and not about Python packages which have some external program's functionality. It is about call to external program and there is a generic answer already. So this is not an answer at all. – astentx Dec 16 '20 at 10:25