473,550 Members | 2,911 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Easier way to get the "here" path?

I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:

from os.path import dirname, realpath, abspath
here = dirname(realpat h(abspath(__fil e__.rstrip("c") )))

In particular, this takes care of the case of symlinked, compiled
scripts, which is fairly common at my workplace, and I imagine in many
*nix evironments.
An illustration:
$echo "print __file__" symlinks/path.py
$ln -s symlinks/path.py
$python
>>import path
path.py
>>reload(path )
path.pyc
<module 'path' from 'path.pyc'>
>>path.__file __
'path.pyc'
>>path.__file__ .rstrip("c")
'path.py'
>>from os.path import abspath, realpath
realpath(path .__file__.rstri p("c"))
'/home/bgolemon/python/symlinks/path.py'
>>realpath(absp ath(path.__file __.rstrip("c")) )
'/home/bgolemon/python/symlinks/symlinks/path.py'
Jul 25 '08 #1
6 4041
bukzor wrote:
I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:
...
If you just need the current path (where it is executed) why not use
os.getcwd()
which returns a string of the absolute path to the module being executed.
$ echo "print __file__" path.py
$ ipython
In [1]: import path
path.pyc

In [2]: import os

In [3]: os.path.join(os .getcwd(), path.__file__.r strip("c"))
Out[3]: '/home/andrew/path.py'
--
Andrew
Jul 26 '08 #2
bukzor wrote:
>>>from os.path import abspath, realpath
realpath(pat h.__file__.rstr ip("c"))
'/home/bgolemon/python/symlinks/path.py'
>>>realpath(abs path(path.__fil e__.rstrip("c") ))
'/home/bgolemon/python/symlinks/symlinks/path.py'
--
http://mail.python.org/mailman/listinfo/python-list
I find it interesting that I get something different:

In [1]: import path
path.pyc

In [2]: path.__file__
Out[2]: 'path.pyc'

In [3]: path.__file__.r strip("c")
Out[3]: 'path.py'

In [4]: from os.path import abspath, realpath

In [5]: realpath(path._ _file__.rstrip( "c"))
Out[5]: '/home/andrew/sym/sym/path.py'

In [6]: realpath(abspat h(path.__file__ .rstrip("c")))
Out[6]: '/home/andrew/sym/sym/path.py'

I get the same thing for realpath() and realpath(abspat h())
It seems to me you can just use:

In [1]: import path
path.pyc

In [2]: from os.path import abspath

In [3]: realpath(path._ _file__.rstrip( "c"))
Out[3]: '/home/andrew/sym/sym/path.py'

By the way, I am in /home/andrew/sym and path is symlinked from
/home/andrew/sym/sym/path.py to /home/andrew/sym/path.py

--
Andrew
Jul 26 '08 #3
On Jul 25, 10:08*pm, bukzor <workithar...@g mail.comwrote:
I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:

from os.path import dirname, realpath, abspath
here = dirname(realpat h(abspath(__fil e__.rstrip("c") )))

In particular, this takes care of the case of symlinked, compiled
scripts, which is fairly common at my workplace, and I imagine in many
*nix evironments.

An illustration:
$echo "print __file__" symlinks/path.py
$ln -s symlinks/path.py
$python>>import path
path.py
>reload(path)

path.pyc
<module 'path' from 'path.pyc'>>>pa th.__file__
'path.pyc'
>path.__file__. rstrip("c")
'path.py'
>from os.path import abspath, realpath
realpath(path. __file__.rstrip ("c"))

'/home/bgolemon/python/symlinks/path.py'>>realp ath(abspath(pat h.__file__.rstr ip("c")))

'/home/bgolemon/python/symlinks/symlinks/path.py'
How about:

import os
import sys
here = os.path.realpat h(os.path.dirna me(sys.argv[0]))

It's a little clearer. :-)
Jul 26 '08 #4
Andrew wrote:
bukzor wrote:
>I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:
...
If you just need the current path (where it is executed) why not use
os.getcwd()
which returns a string of the absolute path to the module being executed.
$ echo "print __file__" path.py
$ ipython
In [1]: import path
path.pyc

In [2]: import os

In [3]: os.path.join(os .getcwd(), path.__file__.r strip("c"))
Out[3]: '/home/andrew/path.py'
--
Andrew
I was thinking of this in the module being imported, but now that I try,
it doesn't work. It is still seeing itself from the symlink's position.

This works, in the module being imported:
$ less path.py
from os.path import realpath
here = realpath(__file __.rstrip("c"))

$ python
>>import path
path.here
'/home/andrew/sym/sym/path.py'

--
Andrew

Jul 26 '08 #5
On Jul 26, 9:19*am, Andrew <alif...@gmail. comwrote:
bukzor wrote:
>>from os.path import abspath, realpath
realpath(path .__file__.rstri p("c"))
'/home/bgolemon/python/symlinks/path.py'
>>realpath(absp ath(path.__file __.rstrip("c")) )
'/home/bgolemon/python/symlinks/symlinks/path.py'
--
http://mail.python.org/mailman/listinfo/python-list

I find it interesting that I get something different:

In [1]: import path
path.pyc

In [2]: path.__file__
Out[2]: 'path.pyc'

In [3]: path.__file__.r strip("c")
Out[3]: 'path.py'

In [4]: from os.path import abspath, realpath

In [5]: realpath(path._ _file__.rstrip( "c"))
Out[5]: '/home/andrew/sym/sym/path.py'

In [6]: realpath(abspat h(path.__file__ .rstrip("c")))
Out[6]: '/home/andrew/sym/sym/path.py'

I get the same thing for realpath() and realpath(abspat h())
It seems to me you can just use:

In [1]: import path
path.pyc

In [2]: from os.path import abspath

In [3]: realpath(path._ _file__.rstrip( "c"))
Out[3]: '/home/andrew/sym/sym/path.py'

By the way, I am in /home/andrew/sym and path is symlinked from
/home/andrew/sym/sym/path.py to /home/andrew/sym/path.py

--
Andrew
As you can see above, I get the wrong think if I do that. It's very
strange that we're getting different things. I'm using python 2.4,
maybe it was updated in 2.5?
Jul 28 '08 #6
On Jul 28, 10:34*am, bukzor <workithar...@g mail.comwrote:
On Jul 26, 9:19*am, Andrew <alif...@gmail. comwrote:
bukzor wrote:
>>>from os.path import abspath, realpath
>>>realpath(pat h.__file__.rstr ip("c"))
'/home/bgolemon/python/symlinks/path.py'
>>>realpath(abs path(path.__fil e__.rstrip("c") ))
'/home/bgolemon/python/symlinks/symlinks/path.py'
--
>http://mail.python.org/mailman/listinfo/python-list
I find it interesting that I get something different:
In [1]: import path
path.pyc
In [2]: path.__file__
Out[2]: 'path.pyc'
In [3]: path.__file__.r strip("c")
Out[3]: 'path.py'
In [4]: from os.path import abspath, realpath
In [5]: realpath(path._ _file__.rstrip( "c"))
Out[5]: '/home/andrew/sym/sym/path.py'
In [6]: realpath(abspat h(path.__file__ .rstrip("c")))
Out[6]: '/home/andrew/sym/sym/path.py'
I get the same thing for realpath() and realpath(abspat h())
It seems to me you can just use:
In [1]: import path
path.pyc
In [2]: from os.path import abspath
In [3]: realpath(path._ _file__.rstrip( "c"))
Out[3]: '/home/andrew/sym/sym/path.py'
By the way, I am in /home/andrew/sym and path is symlinked from
/home/andrew/sym/sym/path.py to /home/andrew/sym/path.py
--
Andrew

As you can see above, I get the wrong think if I do that. It's very
strange that we're getting different things. I'm using python 2.4,
maybe it was updated in 2.5?
After doing a little testing, it seems that realpath was in fact
improved between 2.4 and 2.5. I need to stick with 2.4, so the
abspath() call is still necessary for me.

Regardless, the answer to my question is that there's no good built-in
way to do this. Even the code above fails for some cases (say the
symlink is named just "c"), making the problem non-trivial. To me,
this is a failure of python's "batteries included". Is this worthy of
a PEP? I'd like to add something like "__absfile_ _" or maybe
"os.path.absolu te_script_path( )".

Sample implementation:
def scriptpath():
from inspect import currentframe
file = currentframe(). f_back.f_locals .get('__file__' , None)
if file.endswith(" .pyc"): file = file.rstrip("c" )
from os.path import realpath, abspath

return realpath(abspat h(file))
Testing:
~/python>ls -l foo.py* c sym/*
lrwxrwxrwx 1 bgolemon asic 10 Jul 28 10:46 c -sym/
bar.py*
lrwxrwxrwx 1 bgolemon asic 10 Jul 28 10:38 foo.py -sym/
bar.py*
-rw-rw-r-- 1 bgolemon asic 149 Jul 28 10:57 foo.pyc
-rwxrwx--- 1 bgolemon asic 76 Jul 28 10:53 sym/bar.py*
-rw-rw-r-- 1 bgolemon asic 149 Jul 28 10:58 sym/bar.pyc

~/python>cat sym/bar.py
#!/usr/bin/env python

from scriptpath import scriptpath
print scriptpath()
~/python>./c
/home/bgolemon/python/sym/bar.py

~/python>./sym/bar.py
/home/bgolemon/python/sym/bar.py

~/python>./foo.py
/home/bgolemon/python/sym/bar.py

~/python>python
>>import foo
/home/bgolemon/python/sym/bar.py

~/python>cd sym/
~/python/sym>python
>>import bar
/home/bgolemon/python/sym/bar.py
--Buck
Jul 28 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
9128
by: Jim Hill | last post by:
I've done some Googling around on this and it seems like creating a here document is a bit tricky with Python. Trivial via triple-quoted strings if there's no need for variable interpolation but requiring a long, long formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my question is: Is there a way to produce a very long...
0
2425
by: Tom Dacon | last post by:
"Open .Net Command Window Here" context menu for Windows Explorer: The reg file described below adds a new menu item to Windows Explorer's context menu when you right-click over a folder (or the drive root). The menu item text is "Open .Net Command Window Here". When you click it, it opens a command window positioned at that directory and...
5
12080
by: RodneyDunes | last post by:
My site did validate and now it doesn't. The error I get is the following: document type does not allow element "META" here ....nt-type" content="text/html;charset=iso-8859-1"> Can someone please tell me what I need to change?These are the Meta tags: </head> <meta http-equiv="Content-type" content="text/html;charset=iso-8859-1"> <META...
27
8012
by: Tom Rodman | last post by:
I want to embed a bash script inside the c program. How could you do the below bash snippet in "c"?: cat > /tmp/foo <<\__EOD_ all kinds of nasty stuff in here including single and double quotes and bashslashes .. (note that the here doc delimiter is preceded by a "\" __EOD_
1
6867
by: JohnZing | last post by:
i tried to install asp.net forums all went ok, but after login i always get "Object moved to here." in firefox or "The page cannot be displayed" in IE when i hit refresh, the page loads fine. the problem occurs only when i try to run the application hosted in my hosting provider, not in my local IIS server. any ideas?
1
657
by: ken.carlino | last post by:
Hi, I have the following compile error instantiated from here, I appreciate if someone can help me find out why? g++ -O0 -g3 -Wall -c -fmessage-length=0 -ostddev.o ../stddev.cpp .../stddev.cpp: In member function 'int StatUtils::std_dev(std::vector<int, std::allocator<int> >&, int, int)': .../stddev.cpp:206: warning: converting to 'int'...
2
18881
by: samyuktha takkellapati | last post by:
create or replace trigger emp_trigger after update or delete on employee for each row begin if updating then insert into empupdate(empno,ename,job,mgr,sysdate,sal,comm,deptno) values(:old.empno,:old.ename,:old.job,:old.mgr,:old.hiredate,:old.sal,:old.comm,:old.deptno); elsif deleting then insert into...
2
12019
by: bhavanirayala | last post by:
Hi All, I am getting the following warning while running the perl script Warning is: Quantifier follows nothing before HERE mark in regex m/* << HERE /
0
7758
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7998
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7517
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6098
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5401
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1978
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1093
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
800
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.