How to get the realpath of a symbolic link?

P

Peng Yu

Suppose that I have the following directory and files. I want to get
the canonical path of a file, a directory or a symbolic link.
For example, for 'b' below, I want to get its canonical path as
'/private/tmp/abspath/b'.

However, os.path.abspath('b') gives me '/private/tmp/abspath/b', but
os.path.abspath('/tmp/abspath/b') gives me '/tmp/abspath/b'.
The results are not the same. So, neither os.path.abspath or
os.path.realpath gives me what I want.

I'm wondering if there is a way to get the canonical path
'/private/tmp/abspath/b', no matter whether the argument is 'b' or
'/tmp/abspath/b'.

$./test.py
/private/tmp/abspath/a
/private/tmp/abspath/a
/private/tmp/abspath/a
/private/tmp/abspath/a
/private/tmp/abspath/a
/private/tmp/abspath/b
/tmp/abspath/a
/tmp/abspath/b
$cat test.py
#!/usr/bin/env python

import os.path

print os.path.realpath('a')
print os.path.realpath('b')
print os.path.realpath('/tmp/abspath/a')
print os.path.realpath('/tmp/abspath/b')

print os.path.abspath('a')
print os.path.abspath('b')
print os.path.abspath('/tmp/abspath/a')
print os.path.abspath('/tmp/abspath/b')
$pwd
/tmp/abspath
$gls -Rgtra
..:
total 8
-rw-r--r-- 1 wheel 0 2009-10-31 01:52 a
lrwxr-xr-x 1 wheel 1 2009-10-31 01:52 b -> a
-rwx--x--x 1 wheel 312 2009-10-31 01:54 test.py
drwx------ 5 wheel 170 2009-10-31 01:54 .
drwxrwxrwt 23 wheel 782 2009-10-31 01:56 ..
$gls -lgtr /tmp
lrwxr-xr-x 1 admin 11 2009-05-21 04:28 /tmp -> private/tmp
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top