1

I would like to make sure that the user has mysql installed in order to run a script. Normally I would type in $ mysql in the shell and if it goes to the mysql> prompt I know I'm good. However, how would I do this from within a python script? Something like:

try:
    assert (0 == subprocess.call("mysql -u root -e 'show databases'", shell=True, stderr=subprocess.DEVNULL))
except AssertionError:
    print ("You need to install mysql to run this script")\

What would be the proper way to do this?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    You're (first) checking for the client, not the server. Does it really need to be installed locally? Do you really need the client, or just a server to connect to? If it's the latter, you can just try to connect to it and show an error if it fails. – hdiogenes Feb 28 '20 at 21:17
  • @hdiogenes I need to copy a database from a remote machine to local so I need the db to be installed locally. – David542 Feb 28 '20 at 21:21
  • 1
    Does this answer your question? [Check if a program exists from a python script](https://stackoverflow.com/questions/11210104/check-if-a-program-exists-from-a-python-script) – Matt Clark Feb 28 '20 at 21:23
  • Also, you could use `subprocess.check_call` so you don't have to `assert`. – hdiogenes Feb 28 '20 at 21:27
  • @MattClark yes I suppose it is, though the answer that's been provided I think is better than any of those given on the other page, at least for python3. – David542 Feb 28 '20 at 21:30
  • @MattClark oh I see - thanks that has a nice explanation as well! https://stackoverflow.com/a/34177358/651174 – David542 Feb 28 '20 at 21:33

1 Answers1

1

You can use shutil.which. This is available in Python 3.3+ and will use the same PATH lookup as the operating system you are runnig on.

from shutil import which

def mysql_exists():
    """
    Verifies that the MySQL client is available. Returns true if it exists,
    and false if it does not.
    """
    return which('mysql') is not None
Kyle Laker
  • 86
  • 5
  • @MattClark, I suppose it is. It looks like your comment was posted while I was writing the reply. I apologize for the duplicate information. *edit*: Looks like the comment that I was replying to is no longer visible. – Kyle Laker Feb 28 '20 at 21:34