tags:

views:

97

answers:

4

This may be a noobie questions, but...

So I have a pyc file that I need to use, but I don't have any documentation on it. Is there a way to find out what classes and functions are in it and what variables they take? I don't need to code, just how to run it.

Thanks

+2  A: 

if you stick it on your import path and import it by name, you can use dir

import foo
dir(foo)

you can also use `help'

help(foo)

to get the docstring. Both of these can be used on anything that foo contains as well. Note that bytecode changes between releases so it may or may not work for your version of python. If this is the case, the best that I can say is to try different versions until one works.


If you need to recover the arguments for a function, you first get the argcount

argcount = f.func_code.co_argcount

the arguments are then the first argcount variables of

f.func_code.co_varnames

This doesn't tell you what the function expects them to be and is only really useful if it doesn't have a docstring but it can be done.

aaronasterling
`dir` won't give you full method signatures.
Yuval A
Wow, great minds overlap.
Nathon
Awesome.. This gets me the functions. Is there a way to tell what the functions/class take as variables?
lovefaithswing
@lovefaithswing, see my update
aaronasterling
Thanks! help was what I was looking for. :) That works great.
lovefaithswing
@lovefaithswing, if help doesn't work on the function, try Glen Maynards suggestion. It's less hacky than what I'm suggesting. For classes, just apply it to the `__init__` method of the class.
aaronasterling
+1  A: 

Easiest way http://depython.com

Yuval A
I tried this and all I got back was the help text for the whole documents. ie, a string that said 'This file does x' with no other details
lovefaithswing
A: 

If the code itself has docstrings, and it wasn't generated with optimizations that remove docstrings, you can import the module and peek around:

for foo.pyc

import foo
dir(foo)
help(foo)

If you decide you do need code, there's decompyle.

Nathon
+6  A: 

As long as you can import the file, you can inspect it; it doesn't matter whether it comes from a .py or .pyc.

>>> import getopt
>>> dir(getopt)
['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']
>>> type(getopt.getopt)
<type 'function'>
>>> inspect.getargspec(getopt.getopt)
ArgSpec(args=['args', 'shortopts', 'longopts'], varargs=None, keywords=None, defaults=([],))
>>> help(getopt.getopt)
Help on function getopt in module getopt:
...
Glenn Maynard
+1 for inspect module
aaronasterling
Woooo, reflection.
Nathon
introspection, actually.
Ned Batchelder