How to create a script that list itself ?

  • Thread starter Patrick Allaire
  • Start date
P

Patrick Allaire

How to create a script that list itself ?

I would like to know, where is the script's code is stored once we
start it. I know I can achieve that, using files :

print file('myscript.py','rb').read()

But is there a way / a variable that contains the current file in
memory ?

Thanks.

Xaqc
 
G

Grant Edwards

How to create a script that list itself ?

This is probably about as close as you're going to get:

import sys
pring open(sys.argv[0],'r').read()

And that isn't 100% reliable.
I would like to know, where is the script's code is stored once we
start it.

It isn't. At least none of the implimentations I know of have
the script's source code in memory. The PVM or JVM bytecodes
to which the program has been compiled are in memory somewhere,
and there _may_ be some trick you can use to get at those.
I know I can achieve that, using files :

print file('myscript.py','rb').read()

But is there a way / a variable that contains the current file in
memory ?

I don't believe so.
 
S

Szabolcs Nagy

But is there a way / a variable that contains the current file in
yes: import __main__

you can do:

import inspect
import __main__
print inspect.getsource(__main__)

or simply:

print open(__file__).read()


nsz
 
D

Dave Hansen

How to create a script that list itself ?

Stealing from the old C chestnut:

s="s=%c%s%c;print s%%(34,s,34)";print s%(34,s,34)

I would like to know, where is the script's code is stored once we
start it. I know I can achieve that, using files :

Well, in the above, the script (or rather, the information necessary
to print the script) is actually stored in a string that is part of
the script...

Regards,
-=Dave
 
C

calfdog

########################################

import sys

path = os.path.dirname(sys.argv[0])
print "Path:%s" % (path)



######################################

If you ran this as a script,
This would print the location of where the script itself is running.



Hope it helps!

Rob
 
T

Tim Roberts

Duncan Booth said:
Or a bit shorter:

s='s=%s;print s%%`s`';print s%`s`

It was pointed out to me that the shortest Python program which produces
itself on stdout is:
 
M

Mike Meyer

Tim Roberts said:
It was pointed out to me that the shortest Python program which produces
itself on stdout is:
--

Which, oddly enough, is also the shortest shell program that produces
itself on stdout.

<mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top