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.
If you found this post useful, please consider buying me a coffee.
This post originally appeared on Robin's Blog.
Categorised as: Academic, How To, Programming, Python
[…] 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. […]
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?
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.
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
Love this solution!
I am wondering if the script can identify packages from original Python installation v.s. packages that installed afterwards.
FYI: I am writing documents for my application written in Python, but I don’t remember what packages my application needs additionally.