[Tutor] os.startfile
Steven D'Aprano
steve at pearwood.info
Sun Dec 19 22:16:34 CET 2010
Lang Hurst wrote:
> I have the following in my program:
>
>
> try:
> os.startfile('current_credit.txt')
> except:
> os.system('/usr/bin/xdg-open current_credit.txt')
>
>
> Basically, open a file in notepad if I'm on windows, vim if on my home
> linux computer. It works fine in linux and in Windows through
> virtualbox. The problem is when I take the program to work, it doesn't
> open the file. The computers at work are pretty locked down, so I'm
> thinking it has something to do with the os.startfile command. Are
> there any alternative commands I could try?
You don't give us much information to go on, such as the version of
Python you use, or the operating system on your work desktops, or the
error that you see when you try this, or even if you can open the file
by double-clicking it, but that's okay, because I love guessing games!
I guess that the problem is that your work desktops are, in fact, Apple
Macintoshes running OS-X. Am I close?
Other than that, you shouldn't just blindly ignore the exception raised
by startfile. Not all exceptions mean "You're not running Windows and
there is no startfile command", and you shouldn't catch bare excepts.
You would be better off doing this:
try:
os.startfile('current_credit.txt')
except AttributeError:
# No startfile command, so we're not on Windows.
# Try a Linux command instead.
# (Tested on Fedora, may not work on all distros.)
os.system('/usr/bin/xdg-open current_credit.txt')
That way, when you get a different error, like "file not found" or
"permission denied", you will see what it is, and perhaps get a hint as
to what the problem is.
Python doesn't have super powers. If you can't open a file because the
desktop has been locked down, then Python won't be able to magically
open it. It has no more permissions to do things than you do. There's no
magic command "open files even if I'm not allowed to open them".
--
Steven
More information about the Tutor
mailing list