Satish
Satish

Reputation: 17487

how to use variable in python os.path.exists

Here is my code

[root@04 ~]# python
Python 2.4.3 (#1, May  5 2011, 16:39:10)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> pid = open('/var/run/httpd.pid' , 'r').read()
>>> print pid
24154
>>> os.path.exists('/proc/',pid)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: exists() takes exactly 1 argument (2 given)

Even i tried following, its not working. How do i use variable pid in os.path.exists command?

>>> os.path.exists('/proc/'+pid)
False
>>>

EDIT :

if i type manually PID number it works

>>> print pid
24154

>>> os.path.exists('/proc/24154')
True
>>>

Upvotes: 0

Views: 3860

Answers (2)

user4815162342
user4815162342

Reputation: 155610

The problem is that http.pid doesn't contain just the number, but also a newline character. Since Python's read, unlike shell's backquotes, doesn't strip trailing newlines, the pid variable contains a string like "12345\n" and your code is testing whether "/proc/12345\n" exists.

To correct the problem, call strip() on the string you've read from the file:

os.path.exists(os.path.join('/proc', pid.strip()))

Upvotes: 5

Gareth Latty
Gareth Latty

Reputation: 89097

The best solution is to use os.path.join() here:

os.path.exists(os.path.join('/proc/', pid))

Note, however, that your concatenation should have worked (albeit, it is more fragile and not recommended, compared to os.path.join()), so are you sure the path does exist? False implies it worked and the path does not exist.

The docs note:

Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

Emphasis added. This implies you may have a permission issues, if the path does exist.

Upvotes: 2

Related Questions