Need a cross-platform way to execute binary

Gabriel Genellina gagsl-py at yahoo.com.ar
Sat Feb 10 05:03:28 EST 2007


En Sat, 10 Feb 2007 06:03:40 -0300, techtonik <techtonik at gmail.com>  
escribió:

> Hello, everyb.
>
> Does anybody know simple cross-platform method of probing if
> executable binary is available and launching it.
>
>
> Problem no.1: test if executable file is available
> I'll take windows platform as the most relevant in this case.
> os.access() doesn't handle env PATHEXT and can't detect if a given
> path would be executable or not. Here "executable" means file that
> could be be launched by system() (if there are any other ways - I'd be
> happy to know them)
>
> Suppose I have "ufo2exe" executable two directories up.
>>>> os.access("../../ufo2map.exe", os.X_OK)
> True
>
> However...
>>>> os.access("../../ufo2map", os.X_OK)
> False

That's right - such file does not exist. On Windows, in general, X_OK is  
the same as F_OK: for any existing file, whatever name or extension,  
returns True. Permissions are managed thru ACL and this simple function  
does NOT consider them.

>
> But...
>>>> os.system("..\..\ufo2map")
> ---- ufo2map 1.0 ----
> 0

(Beware of single \ on normal strings!)
Use win32api.FindExecutable; should return the full path to ufo2map.exe.  
"foo.txt" would return notepad.exe (or whatever you have associated to  
text files). That is exactly what would be launched by os.system("foo.txt")

> Problem no.2: launch executable file
> The same windows platform again. All python commands are using forward
> slashes for paths, but system doesn't handle this situation (it could
> at least try to convert immediate forward slashes to backwards)

Use os.path.normpath on the filename. (If you got it from FindExecutable  
above, that would not be needed)

> os.access() thinks this file is executable, but os.system() fails ...
>>>> os.access("../../ufo2map.exe", os.X_OK)
> True
>>>> os.system("../../ufo2map.exe")
> '..' is not recognized as an internal or external command,
> operable program or batch file.
> 1
>
> the contrary - access() fails to tell this path can be launched, but
> file Is executable,  ...
>>>> os.access("..\..\ufo2map", os.X_OK)
> False

Same as above - such file does not exist.

>>>> os.system("..\..\ufo2map")
> ---- ufo2map 1.0 ----
> 0

> Is there any workaround in Python or I have to stick with platforms-
> specific quirks?
> I'm using Python 2.4.2

I think you will have to treat each platform differently. Just for  
starting, the concept of "executable" is not the same across platforms.  
But you could make some generic functions (with different implementations  
on different platforms).

-- 
Gabriel Genellina




More information about the Python-list mailing list