how to get file name of the running .py file

J

Jason Jiang

Hi,

How to get the name of the running .py file like the macro _FILE_ in C?

Thanks.
Jason
 
L

Larry Bates

Jason said:
Hi,

How to get the name of the running .py file like the macro _FILE_ in C?

Thanks.
Jason
import os
import sys
print sys.argv[0]

or if you just want the script and not the full path

print os.path.basename(sys.argv[0])

-Larry Bates
 
J

Jason Jiang

B

Bill Pursell

Jason said:
Hi,

How to get the name of the running .py file like the macro _FILE_ in C?

There are many ways--IMO the easiest is with __file__:
[tmp]$ cat foo.py
#!/usr/bin/env python

print "The name of the file is:%s"%__file__
[tmp]$ ./foo.py
The name of the file is:./foo.py
 
F

Fredrik Lundh

import os
import sys
print sys.argv[0]

or if you just want the script and not the full path

print os.path.basename(sys.argv[0])

except that __FILE__ is the name of the current source file, not the
name of the main program.

the global name __file__ is a better choice; when definied, it points to
the file from which the current module was loaded (this might be a byte
code file or a shared library).

also see:

http://pyref.infogami.com/__file__

</F>
 

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
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top