Does executable exist in Python?

0 votes
In Python, is there a portable and simple way to test if an executable program exists?

I don't want to search PATH manually or something involving trying to execute it with Popen & al and see if it fails (that's what I'm doing now, but imagine it's launch missiles)
Sep 21, 2018 in IoT (Internet of Things) by Annie97
• 2,190 points
21 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

This is a way I can think of;

def which(program):
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

Edit: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command.

Edit: Updated to use os.path.isfile() instead of os.path.exists() per comments.

Edit: path.strip('"') seems like the wrong thing to do here. Neither Windows nor POSIX appear to encourage quoted PATH items.

answered Sep 21, 2018 by Upasana
• 7,480 points

Related Questions In IoT (Internet of Things)

0 votes
1 answer
0 votes
1 answer

MQTT : Web Socket in python

You can simply create a configuration file ...READ MORE

answered Apr 15 in IoT (Internet of Things) by Shubham
• 12,110 points
38 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
19 views
0 votes
1 answer

What is the time taken by a 200 byte message for transmission in a beacon-enabled network?

Now, data rates of IEEE 802.15.4 are ...READ MORE

answered Aug 23, 2018 in IoT (Internet of Things) by Upasana
• 7,480 points
21 views
0 votes
1 answer

How to trigger Python script on Raspberry Pi from Node-Red

Node-RED supplies an exec node as part ...READ MORE

answered Sep 14, 2018 in IoT (Internet of Things) by Upasana
• 7,480 points
684 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.