Python os.path.isdir检查失败
我有下面的代码,我试图检查目录“Gerrits/HEAD/wlan”,然后执行一些操作,如果出于某种原因,即使目录存在,检查目录的条件仍然失败? if有什么问题吗condition@if(os.path.isdir(SCRIPT_ROOT+“/Gerrits/HEAD/wlan”):如下 错误:-Python os.path.isdir检查失败,python,unix,Python,Unix,我有下面的代码,我试图检查目录“Gerrits/HEAD/wlan”,然后执行一些操作,如果出于某种原因,即使目录存在,检查目录的条件仍然失败? if有什么问题吗condition@if(os.path.isdir(SCRIPT_ROOT+“/Gerrits/HEAD/wlan”):如下 错误:- SCRIPT_ROOT/Gerrits/HEAD/wlan doesn't exist,cloning it Traceback (most recent call last): File "te
SCRIPT_ROOT/Gerrits/HEAD/wlan doesn't exist,cloning it
Traceback (most recent call last):
File "test.py", line 21, in <module>
main()
File "test.py", line 16, in main
os.makedirs("Gerrits/HEAD/wlan")
File "/usr/lib/python2.6/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: 'Gerrits/HEAD/wlan'
SCRIPT\u ROOT/Gerrits/HEAD/wlan不存在,正在克隆它
回溯(最近一次呼叫最后一次):
文件“test.py”,第21行,在
main()
文件“test.py”,第16行,在main中
os.makedirs(“Gerrits/HEAD/wlan”)
makedirs中的文件“/usr/lib/python2.6/os.py”,第157行
mkdir(名称、模式)
OSError:[Errno 17]文件存在:“Gerrits/HEAD/wlan”
将.strip()
添加到communicate()[0]
调用中,代码原样包括输出中的尾随换行符
可以肯定的是,我刚刚用Python2.5在linux机器上测试了您的脚本
import os
import subprocess
from subprocess import check_call
SCRIPT_ROOT=subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0].strip()
print SCRIPT_ROOT
def main ():
if (os.path.isdir(SCRIPT_ROOT + "/Gerrits/HEAD/wlan")):
print "SCRIPT_ROOT/Gerrits/HEAD/wlan already exists,cloning it again to the tip"
check_call("rm -rf %s/Gerrits/HEAD/wlan" % SCRIPT_ROOT, shell=True)
check_call("cd Gerrits/HEAD",shell=True)
else:
print "SCRIPT_ROOT/Gerrits/HEAD/wlan doesn't exist,cloning it"
os.makedirs("Gerrits/HEAD/wlan")
check_call("cd Gerrits/HEAD",shell=True)
currdir=subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0].strip()
if __name__ == '__main__':
main()
其输出:
vlazarenko@xx:~$ python o.py
/media/home/vlazarenko
SCRIPT_ROOT/Gerrits/HEAD/wlan already exists,cloning it again to the tip
当我在这里执行这行代码时:
SCRIPT_ROOT=subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]
“SCRIPT\u ROOT
的值后面有一个换行符。”
>>> import os
>>> import subprocess
>>> ROOT = subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]
>>> ROOT
'/Users/bgporter/personal\n'
…这就是我打电话的原因
if (os.path.isdir(SCRIPT_ROOT + "/Gerrits/HEAD/wlan")):
表现得和你希望的不一样。您可以对该值调用strip(),或者如果您始终希望获取当前工作目录,则可以通过调用
类似地,您可以使用该函数递归地删除您不想要的目录,而不是剥离 提问前请把问题缩小范围。这是太多的东西了。@JeremyVisser-这正是我所做的,请再通读一遍,即使在添加了.strip()之后,它仍然认为它不存在经过修改的完整脚本,在我的环境中确实有效,即使我在我的homedir中复制了
Gerrits/HEAD/wlan
。我切换到了os.getcwd()但是现在删除失败了@“check_调用(“rm-rf$SCRIPT_ROOT/Gerrits/HEAD/wlan”,shell=True)”失败了。。。如何更改此rm语句以删除整个“Gerrits/HEAD/wlan”,如果它存在…$SCRIPT\u ROOT
将不会计算,它不是shell:)您需要像在代码的其他部分中那样对其执行+
操作,或者使用其他字符串格式方法。谢谢,“check\u call(“cd Gerrits/HEAD”,shell=True)”为你工作?我改为os.getcwd,但不知何故脚本仍然认为目录不存在。我现在认为“check_call(“rm-rf$script_ROOT/Gerrits/HEAD/wlan”,shell=True)”失败了。。。如何更改此rm语句以删除整个“Gerrits/HEAD/wlan”,如果它存在。。。
if (os.path.isdir(SCRIPT_ROOT + "/Gerrits/HEAD/wlan")):