2016-05-15 20 views
0

重複編輯:不,我做到了,但它不想啓動Firefox。 我正在製作一個cortana/siri助理的東西,我想讓它說我打電話的時候打開網頁瀏覽器。所以我做了if部分,但我只是需要它啓動firefox.exe我嘗試了不同的東西,我得到一個錯誤。這是代碼。請幫忙!它的工作原理與打開記事本,但沒有Firefox的..如何在Python中打開外部程序

#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']) 
+2

使用'firefox.exe'的絕對路徑。 – fsp

+0

可能的重複[如何從python執行程序? os.system失敗,由於路徑中的空格](http://stackoverflow.com/questions/204017/how-do-i-execute-a-program-from-python-os-system-fails-due-to-spaces -in-path) –

+1

記事本通常位於PATH變量下的system32文件夾中,但firefox不太可能。 – YOU

回答

1

簡短的回答是,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.systemsubprocess.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) 
+0

(我也複製了我的firefox位置的確切路徑)好吧,我完成了子程序代碼,當我嘗試從它啓動Firefox時,它說:Traceback(最近調用最後一個): 文件「Danbot.py 「,第33行,在 subprocess.Popen(['C:\ Program Files \ Mozilla Firefox \ firefox.exe']) 文件」c:\ hp \ bin \ python \ lib \ subprocess.py「,第593行,in __init__ errread,errwrite) WindowsError:[錯誤22]文件名稱,目錄名稱或卷的文件「c:\ hp \ bin \ python \ lib \ subprocess.py」,行793,在_execute_child中 startupinfo) 標籤語法不正確 – noone

+0

@Dan據猜測,這可能是因爲'\ f'被Python解釋爲換頁的轉義序列。將'\ f'改爲'\\ f'。 –

+0

什麼\ f?我沒有使用\ f ..的任何東西? – noone

相關問題