0

If for example I was using the following code to open an application:

import os
os.system("open /Applications/IAmAnApp.app")

But if there is no such application such as IAmAnApp, it will display this message:

The file /Users/Username/Desktop/Python/iamanapp does not exist.

I tried using try then except, but it's not an error, just a message.

How can I disable this message and just let the code continue?

user3875728
  • 117
  • 5

5 Answers5

0

If this is a message printed by open (whatever this command is), how about testing for file existence before?

os.system("test -f /Applications/IAmAnApp.app && open /Applications/IAmAnApp.app")
adl
  • 15,627
  • 6
  • 51
  • 65
0
import subprocess
try:
    subprocess.call(["open /Applications/IAmAnApp.app"])
except OSError:
    dosomething_else
petkostas
  • 7,250
  • 3
  • 26
  • 29
  • Thank you! I would've used that except I was trying to teach my friend about the open command using import os. I should've been more clear about that! – user3875728 Aug 10 '14 at 22:28
0

You could use a shell to redirect the output.

os.system('bash -c "open /Applications/IAmAnApp.app &> /dev/null"')
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
0

Here's a quick and easy method: use os.path.isdir to detect the presence of the app. Here’s an example:

import os

app_path = os.path.join('/Applications', 'Safari.app')
if os.path.isdir(app_path):
    print 'installed!'
else:
    print 'not installed!'

Note that you have to use isdir, not isfile, because OS X .app bundles are really directories that get special treatment from the Finder. This also seems to work for symlinks, but I don’t know how it would work for aliases.

alexwlchan
  • 5,699
  • 7
  • 38
  • 49
0

You should use the subprocess module which is intended to replace os.system:

import subprocess
subprocess.Popen(['open', '/Applications/IAmAnApp.app'],
    stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115