Robin's Blog

How to: Find out what modules a Python script requires

I do a lot of my academic programming in Python, and – even though I often write about the importance of reproducible research – I don’t always document my code very well. This sometimes leads to problems where I have some code running fine, but I don’t know which modules it requires. These could be external libraries, or modules I’ve written myself – and it’s very frustrating to have to work out the module requirements by trial and error if I transfer the code to a new machine.

However, today I’ve realised there’s a better way: the modulefinder module. I’ve written a short piece of code which will produce a list of all of the ‘base’ or ‘root’ modules (for example, if you run from LandsatUtils.metadata import parse_metadata, then this code will record LandsatUtils) that your code uses, so you know which you need to install.

Hopefully, like me, it’ll save you some time.


Categorised as: Academic, How To, Programming, Python


4 Comments

  1. […] não deu tão certo quanto eu esperava, mas as surpresas foram bem interessantes. Usei um script dessa página aqui que usa uma biblioteca chamada modulefinder que consegue fazer esse trabalho de exibir as coisas. […]

  2. Developer says:

    A big problem I am facing is that if someone mistakenly imports using *, it is very hard to find the altarnative “from xxx import this and that”. Is your script capable of finding those requirements?

  3. Robin Wilson says:

    Unfortunately not, sorry. I don’t know of a script that does that, and I suspect it’d be quite difficult to do – do let me know if you come across anything though.

  4. Abhi says:

    Hi Robin,
    This is general query , however want python expert advice.
    I’m working as Windows Server & VMware Admin , how I can move to python scripting to do automation( in future development)!
    I have already started learning basics of python , but getting frequent problem to understand scripts available in GitHub. I know bit of Powershell scripting , but in-case of python , how to list down all available modules ? Command syntax ?
    Any suggestion to follow any specific blog / tutorial site, please suggest.
    Thanks,
    Abhi

Leave a Reply

Your email address will not be published. Required fields are marked *