Is it possible to access the python script source code passed to python by standard in?

This is a bit of a random question, which is more out of curiosity than any particular need.

Is it possible to write some python code that will print some things, including the source code itself, without the python code stored in the file? For example, by doing something similar in 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 this conclusion:

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 cannot be done, but given the possibilities of introspecting python, I was curious to see if this level extends to this level.

+3
source share
4 answers

What is the closest I get:

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

... , ( stdin) . __main__.

Update:

dis , , :

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

:

$ echo -e "import  __main__,dis;print dis.dis(__main__)\ndef x():\n pass" | python
None
+2

, , . , ( ).

Quine, Python:

quine = 'quine = %r\r\nprint quine %% quine'
print quine % quine

quines . , , ...:)

+3

print open(__file__).read(),

UNIX, , Windows. , , . a >

( ), , sys.stdin, . , quines (, ) Python, , . , , .

, , , , , . , Python , . (, shebang, , ).

+1

readline , , , , , ,

+1

Source: https://habr.com/ru/post/1752420/


All Articles