0

我有以下代码,我试图检查目录“Gerrits/HEAD/wlan”,然后执行一些操作,出于某种原因,如果即使目录存在,检查目录的条件仍然失败?if condition@if (os.path.isdir(SCRIPT_ROOT + "/Gerrits/HEAD/wlan")) 有什么问题:下面

import os
import subprocess
from subprocess import check_call

SCRIPT_ROOT=subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]
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 $SCRIPT_ROOT/Gerrits/HEAD/wlan ", 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]

if __name__ == '__main__':
    main()

错误:-

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'
4

2 回答 2

1

添加.strip()到您的communicate()[0]调用中,代码原样在输出中包含尾随换行符。

可以肯定的是,我刚刚在带有 Python 2.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
于 2012-12-28T01:25:05.307 回答
1

当我在这里执行这行代码时:

SCRIPT_ROOT=subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]

...的值SCRIPT_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() ,或者如果您总是想获取当前工作目录,您可以通过调用更轻松地做到这一点os.getcwd()

同样,您可以使用该os.removedirs()函数递归地删除您不想要的目录,而不是脱壳。

于 2012-12-28T01:25:23.010 回答