Re: portable way of locating an executable (like which)

Discussion in 'Python' started by Chris Angelico, Sep 21, 2012.

  1. On Fri, Sep 21, 2012 at 8:32 AM, Ian Kelly <> wrote:
    > On Thu, Sep 20, 2012 at 4:21 PM, Chris Angelico <> wrote:
    >> os.sep is the directory separator, but os.pathsep may be what you
    >> want. Between that and os.getenv('path') you can at least get the
    >> directories. Then on Windows, you also need to check out
    >> os.getenv('pathext') and split _that_ on the semicolon, and try each
    >> of those as a file extension. I'm not sure whether or not Windows will
    >> add extensions from pathext if one is given on the command line - for
    >> instance, if typing "foo.exe" will search for "foo.exe.bat" - but the
    >> basics are there.

    >
    > Easy enough to test:
    >
    > C:\>echo echo hello! > foo.exe.bat
    >
    > C:\>foo.exe
    > hello!
    >
    > Yup, it does. It looks like it tries it without the extension first, though:
    >
    > C:\>copy c:\windows\notepad.exe foo.exe
    > 1 file(s) copied.
    >
    > C:\>foo.exe
    > [starts notepad]


    Well, at least it's consistent. Makes your PATH extremely sensitive,
    though, easy for anyone to inject executables into it. But then, you
    can already do that by putting them in the current directory, so
    that's not really any different.

    Jason's solution looks fine apart from the PATHEXT requirement, so if
    you know you have the full filename and you don't care if the actual
    command interpreter will do exactly the same, that'll do you fine.

    Is this something that might want to be a function in the os module?
    Particularly so if, as I suspect there might be, there's a Win32 API
    function that precisely replicates the behaviour of executable
    invocation. A while since I've done much Windows programming but I
    think there's a SearchPath function?

    ChrisA
     
    Chris Angelico, Sep 21, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gelonida N
    Replies:
    4
    Views:
    219
    Ramchandra Apte
    Sep 23, 2012
  2. Mark Lawrence
    Replies:
    0
    Views:
    178
    Mark Lawrence
    Sep 20, 2012
  3. Chris Angelico
    Replies:
    0
    Views:
    206
    Chris Angelico
    Sep 20, 2012
  4. Ian Kelly
    Replies:
    0
    Views:
    215
    Ian Kelly
    Sep 20, 2012
  5. Gelonida N
    Replies:
    0
    Views:
    196
    Gelonida N
    Sep 21, 2012
Loading...

Share This Page