I'm writing a general purpose printing class:
from __future__ import division
import os.path
class pprint:
def __init__(self, name, path=None):
self.name = name
if path == None:
#Where we define the path
???
self.path = path
self.complete_name = os.path.join(path, name)
self.f = open(complete_name, "w")
def __call__(text):
self.f.write(text + "\n")
print text
The constructor takes the name of the file to write to and an optional argument containing that file's path. If the user does not specify the path, I want it to write to the directory of the calling program. The only thing I don't know how to do is the latter conditional: if no path is specified, assume that the path is that of the calling function.
How do I find this out? Essentially, I want to look on the python function stack, find out what function is calling pprint
, find the path of that file, and then set path
to be the path of that file. I, however, know NOTHING about how the python function stack works. How do I do this?
Thanks!
EDIT: I don't want the path of the __main__
file. If I have a.py
call b.py
and b.py
call pprint.py
, I don't want the path of a.py
. The paths of a.py
and b.py
might be quite different.
EDIT 2: I'm using Python 2.7.6. I'm on Ubuntu 14.04, if that's relevant. I use the thing that came built-in, with some other stuff like numpy, scipy, pylab, etc. appended. I have no IDE. I use vim and Terminal. EDIT on EDIT: Whoops! As one post commented, Ubuntu built-in python IS CPython. My bad. So, I am using CPython...