如何在Python中使用变量检查os.path.exists

0 投票
2 回答
3710 浏览
提问于 2025-04-17 18:01

这是我的代码

[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)

我尝试了以下方法,但还是不行。我该如何在 os.path.exists 命令中使用变量 pid 呢?

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

编辑:

如果我手动输入PID号码,它就能正常工作

>>> print pid
24154

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

2 个回答

2

这里最好的解决办法是使用 os.path.join() 方法:

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

不过要注意,你之前的路径拼接应该是能工作的(虽然这种方法比较脆弱,不推荐使用,跟 os.path.join() 相比),所以你确定这个路径是存在的吗? False 表示它工作了,但路径并不存在。

文档中提到:

如果路径指向一个存在的路径或打开的文件描述符,则返回 True。如果是损坏的符号链接,则返回 False。在某些平台上,如果没有权限执行 os.stat() 来检查请求的文件,即使路径实际上存在,这个函数也可能返回 False。

强调一下。这意味着如果路径确实存在,你可能会遇到权限问题。

5

问题在于,http.pid 里不仅仅是一个数字,还有一个换行符。因为Python的 read 方法和shell的反引号不同,它不会自动去掉末尾的换行符,所以 pid 变量的内容变成了像 "12345\n" 这样的字符串,而你的代码在检查 "/proc/12345\n" 是否存在。

要解决这个问题,可以对从文件中读取的字符串使用 strip() 方法:

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

撰写回答