Bailey_xii
Bailey_xii

Reputation: 89

subprocess in python: file does not exist

I run into this error while trying to launch an application from my Mac by using subprocess command.

I tried this and it still working normally

import subprocess

appname = "Microsoft Word"
appname1 = appname + ".app"
subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)

But however, when I applied it to my function. It said the file does not exist.

import re
import subprocess

def myCommand(command):
    elif 'launch' in command:
        reg_ex = re.search('launch(.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)

And it returned like this:

Command: Launch Microsoft Word
The file /Applications/ microsoft word.app does not exist.

Upvotes: 0

Views: 375

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

problem is that your regex captures the space before the argument of launch, resulting in a full filename like /Applications/ microsoft word.app instead of /Applications/microsoft word.app

That (or a simple str.split or better: shlex.split) would fix it:

re.search('launch\s+(.*)', command)

note that 'launch' in command is a bit fragile to detect if the command is really launch. What if the arguments contain launch. Use shlex.split to be able to parse your command line properly (with quote support) instead:

import shlex

command = ' launch "my application"'

args = shlex.split(command)
# at this point, args = ['launch', 'my application']
if args[0] == "launch" and len(args)==2:
    p = subprocess.Popen(["open","-n",os.path.join("/Applications",args[1])],stdout=subprocess.PIPE)

Upvotes: 1

Related Questions