wsdzbm
wsdzbm

Reputation: 3660

Is there any function in Python similar to 'which' and 'open' in matlab?

In matlab, it's easy to find the path to a '.m' file by 'which XX.m' and also convenient to view the code by 'open XXX.m'.

In Python, is there any similar command?

Upvotes: 1

Views: 108

Answers (1)

abarnert
abarnert

Reputation: 365697

If you've already imported the module (or can do so without any harm), the inspect module is probably what you want. For example, getsourcefile will give you the path to the file the module was loaded from, while getsource will give you the source code.

Of course these don't always work, because some Python modules can be extension modules written in C, or cached .pyc files that someone installed without the .py file, or bundled up in a .zip file instead of a flat directory, or anything else you can think up and write a loader for… But in those cases, nothing could work; when something reasonable could work, inspect will.

There's nothing quite like the open function because Matlab is a GUI environment, whereas Python is just a language that can run in a wide variety of different GUIs or none at all, but once you know the path, presumably you can figure out how to open it in your IDE session or in your favorite text editor or whatever.


If you can't actually import the module (maybe the reason you're asking is because import XX is failing and you want to find the code to fix the problem…), but want to know which module would be imported, that's not quite as easy in Python 2.7 as in 3.4, but the imp module is often good enough—in particular, imp.find_module('XX') will usually get you what you want (as long as you pay attention to the explanation about packages in the docs).

Upvotes: 1

Related Questions