0

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.
2
  • 1
    Is the space between /Applications/ and "Microsoft word" word a typo or is it actually there in the error message? If it is actually there, that could be your problem... maybe try a regex that eliminates a no y spaces between the launch word and the rest of the expression? E.g. re.search('launch\s*(.*)' Commented Jul 31, 2019 at 8:11
  • @GMc: Ohhh, it worked. Thanks man. I was really silly not to realize the problem is in the space between. Commented Jul 31, 2019 at 8:24

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

OMG! It worked. And thank you for the advice man. I definitely gonna use that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.