Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access the source code of a python script passed to python on standard in?

This is a bit of a random question that is more out of curiosity than any specific need.

Is it possible to write some python code that will print some stuff out, including the source code itself, without having the python code stored in a file? For example, doing something like this at the Bash prompt:

$ echo '
> print "The Code:"
> PrintScript() # What would this function look like?
> for i in range(5):
>     print i,
> print "!"
> ' | python

and get an output like this:

The Code:
print "The Code:"
PrintScript() # What would this function look like?
for i in range(5):
    print i,
print "!"
0 1 2 3 4 5 !

I suspect that this probably can't be done, but given python's introspection capabilities, I was curious to know whether it extended to this level.

like image 533
DrAl Avatar asked Feb 27 '23 18:02

DrAl


1 Answers

That's the closest I'm getting:

echo 'import  __main__,inspect;print inspect.getsource(__main__)' | python

which fails... In any case, the original code is eaten up (read from stdin) by the interpreter at startup. At most you may be able to get to the compiled code, again through the __main__ module.

Update:

The dis module is supposed to give you a disassembly of all functions in a module, but even that one isn't seeing any code:

$ echo -e 'import  __main__,dis;print dis.dis(__main__)' | python
None

And even when I throw in a function:

$ echo -e "import  __main__,dis;print dis.dis(__main__)\ndef x():\n pass" | python
None
like image 72
Wim Avatar answered Apr 26 '23 01:04

Wim