예제 #1
0
def main():
    
    global myarg0,myarg1,myarg2
    
    try:
        myarg0
    except NameError:
        print "please specify the path"
        return
    
    try:
        myarg1
    except NameError:
        myarg1 = "------"
    
    if myarg1 is not str or len(myarg1) <= 6: myarg1 = "------"
    
    try:
        myarg2
    except NameError:
        myarg2 = "n"
    
    f = File(myarg0)
    if (not f.isDirectory()) and (not f.isFile()):
        print "No such file or directory",myarg0
        return
    
    printfiles(f,myarg1,0,myarg2)
예제 #2
0
파일: theme.py 프로젝트: yxxcrtd/jitar2.0
    def execute(self):
        if self.loginUser == None:
            return self.LOGIN

        if self.isAdmin() == False:
            self.addActionError(u"您你没有管理的权限!")
            return self.ERROR

        if request.getMethod() == "POST":
            tmpl = self.params.safeGetStringParam("tmpl")
            if tmpl == "":
                self.subject.setThemeName(None)
            else:
                self.subject.setThemeName(tmpl)
            self.subjectService.saveOrUpdateSubject(self.subject)
            return self.SUCCESS

        # 查找所有样式
        themeFolder = application.getRealPath(
            "/") + "theme" + File.separator + "subject" + File.separator
        file = File(themeFolder)
        if file.exists() == True:
            theme_list = []
            fs = file.list()
            for theme in fs:
                fd = File(themeFolder + theme)
                if fd.isDirectory() == True:
                    theme_list.append(theme)
            if len(theme_list) > 0:
                request.setAttribute("theme_list", theme_list)

        request.setAttribute("subject", self.subject)
        return "/WEB-INF/subjectmanage/theme.ftl"
예제 #3
0
    def extract(self):
        """
        Deploy resource model elements at the domain level, including multi-tenant elements.
        """
        _method_name = 'extract'

        resource_file = self._model_context.get_domain_resource_file()
        self._logger.info("WLSDPLY-10000",
                          resource_file,
                          method_name=_method_name,
                          class_name=self._class_name)

        # create the target file directory, if needed
        resource_dir = File(resource_file).getParentFile()
        if (not resource_dir.isDirectory()) and (not resource_dir.mkdirs()):
            mkdir_ex = exception_helper.create_deploy_exception(
                'WLSDPLY-10001', resource_dir)
            raise mkdir_ex

        # build the resource file structure from the kubernetes section of the model
        resource_dict = self._create_domain_resource_dictionary()

        # revise the resource file structure with values from command line, and elsewhere in model
        self._update_resource_dictionary(resource_dict)

        # write the resource file structure to the output file
        writer = PythonToFile(resource_dict)

        writer.write_to_file(resource_file)
        return
예제 #4
0
def stat(path):
    """stat(path) -> stat result

    Perform a stat system call on the given path.

    The Java stat implementation only returns a small subset of
    the standard fields: size, modification time and change time.
    """
    abs_path = sys.getPath(path)
    try:
        return stat_result.from_jnastat(_posix.stat(abs_path))
    except NotImplementedError:
        pass
    except:
        raise
    f = File(abs_path)
    if not f.exists():
        raise OSError(errno.ENOENT, strerror(errno.ENOENT), path)
    size = f.length()
    mtime = f.lastModified() / 1000.0
    mode = 0
    if f.isDirectory():
        mode = _stat.S_IFDIR
    elif f.isFile():
        mode = _stat.S_IFREG
    if f.canRead():
        mode = mode | _stat.S_IREAD
    if f.canWrite():
        mode = mode | _stat.S_IWRITE
    return stat_result((mode, 0, 0, 0, 0, 0, size, mtime, mtime, 0))
예제 #5
0
def validateDirectory(Framework):
    exportDirectory = Framework.getTriggerCIData("Export Directory")
    if exportDirectory != None and exportDirectory != "":
        dir = File(exportDirectory)
        if dir.exists() and dir.isDirectory():
            return 1
        return 0
예제 #6
0
def validateDirectory(Framework):
    exportDirectory = Framework.getTriggerCIData("Export Directory")
    if exportDirectory != None and exportDirectory != "":
        dir = File(exportDirectory)
        if dir.exists() and dir.isDirectory():
            return 1
        return 0
예제 #7
0
def stat(path):
    """stat(path) -> stat result

    Perform a stat system call on the given path.

    The Java stat implementation only returns a small subset of
    the standard fields: size, modification time and change time.
    """
    abs_path = sys.getPath(path)
    try:
        return stat_result.from_jnastat(_posix.stat(abs_path))
    except NotImplementedError:
        pass
    except:
        raise
    f = File(abs_path)
    if not f.exists():
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    size = f.length()
    mtime = f.lastModified() / 1000.0
    mode = 0
    if f.isDirectory():
        mode = _stat.S_IFDIR
    elif f.isFile():
        mode = _stat.S_IFREG
    if f.canRead():
        mode = mode | _stat.S_IREAD
    if f.canWrite():
        mode = mode | _stat.S_IWRITE
    return stat_result((mode, 0, 0, 0, 0, 0, size, mtime, mtime, 0))
예제 #8
0
 def empty_user(self):
     strRootDir = request.getServletContext().getRealPath("/")
     strUserHtmlDir = strRootDir + "html" + File.separator + "user" + File.separator
     dirFile = File(strUserHtmlDir)
     if dirFile.exists() == False or dirFile.isDirectory() == False:
         request.setAttribute("errorMessage", u"用户缓存文件夹不存在!")
         return
     
     FileUtils.deleteQuietly(dirFile)
     request.setAttribute("errorMessage", u"删除所有用户缓存完毕!")
예제 #9
0
def EzDirectoryOpenDialog(initialDirectory, stage=None):
    from javafx.stage import DirectoryChooser
    from java.io import File
    dlg = DirectoryChooser()
    if initialDirectory:
        f = File(initialDirectory)
        if f.exists() and f.isDirectory():
            dlg.setInitialDirectory(f);
    dlg.setTitle("Select Folder");
    return dlg.showDialog(stage)
예제 #10
0
def rmdir(path):
    """rmdir(path)

    Remove a directory."""
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    elif not f.isDirectory():
        raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path)
    elif not f.delete():
        raise OSError(0, "couldn't delete directory", path)
예제 #11
0
def rmdir(path):
    """rmdir(path)

    Remove a directory."""
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(errno.ENOENT, strerror(errno.ENOENT), path)
    elif not f.isDirectory():
        raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path)
    elif not f.delete():
        raise OSError(0, "couldn't delete directory", path)
예제 #12
0
def EzFileDialog(initialFile, save, stage=None):
    from javafx.stage import FileChooser
    from java.io import File
    dlg = FileChooser()
    if initialFile:
        f = File(initialFile)
        if f.exists():
            if f.isDirectory(): dlg.setInitialDirectory(f)
            if f.isFile():      dlg.setInitialFileName(f.getAbsolutePath());
    dlg.setTitle("Select File");
    if save: return dlg.showSaveDialog(stage);
    else:    return dlg.showOpenDialog(stage);
예제 #13
0
def addToClasspath(dirPath):
    rootDir = File(dirPath)
    if (rootDir.isFile()):
        sys.path = sys.path + [dirPath]
        return
    if (rootDir.isDirectory()):
        sys.path = sys.path + [dirPath]
        # recursively add the subdirectories and the jar files
        for i in rootDir.listFiles():
            if (i.isDirectory()):
                addToClasspath(i.getPath())
            if (i.isFile()):
                if ((i.getName())[-4:] == ".jar"):
                    sys.path = sys.path + [i.getAbsolutePath()]
예제 #14
0
def mkdir(path, mode='ignored'):
    """mkdir(path [, mode=0777])

    Create a directory.

    The optional parameter is currently ignored.
    """
    # XXX: use _posix.mkdir when we can get the real errno upon failure
    fp = File(sys.getPath(path))
    if not fp.mkdir():
        if fp.isDirectory() or fp.isFile():
            err = errno.EEXIST
        else:
            err = 0
        msg = strerror(err) if err else "couldn't make directory"
        raise OSError(err, msg, path)
예제 #15
0
def mkdir(path, mode='ignored'):
    """mkdir(path [, mode=0777])

    Create a directory.

    The optional parameter is currently ignored.
    """
    # XXX: use _posix.mkdir when we can get the real errno upon failure
    fp = File(sys.getPath(path))
    if not fp.mkdir():
        if fp.isDirectory() or fp.isFile():
            err = errno.EEXIST
        else:
            err = 0
        msg = errno.strerror(err) if err else "couldn't make directory"
        raise OSError(err, msg, path)
    def __get_manifest(self, source_path, from_archive):
        """
        Returns the manifest object for the specified path.
        The source path may be a jar, or an exploded path.
        :param source_path: the source path to be checked
        :param from_archive: if True, use the manifest from the archive, otherwise from the file system
        :return: the manifest, or None if it is not present
        :raises: IOException: if there are problems reading an existing manifest
        """
        manifest = None
        if string_utils.is_empty(source_path):
            return manifest

        source_path = self.model_context.replace_token_string(source_path)

        if from_archive and deployer_utils.is_path_into_archive(source_path):
            return self.archive_helper.get_manifest(source_path)

        else:
            if not os.path.isabs(source_path):
                # if this was in archive, it has been expanded under domain home.
                # or it may be a relative file intentionally placed under domain home.
                source_file = File(File(self.model_context.get_domain_home()), source_path)
            else:
                source_file = File(source_path)

            if source_file.isDirectory():
                # read the manifest directly from the file system
                manifest_file = File(source_file, MANIFEST_NAME)
                if manifest_file.exists():
                    stream = None
                    try:
                        stream = FileInputStream(manifest_file)
                        manifest = Manifest(stream)
                    finally:
                        if stream is not None:
                            try:
                                stream.close()
                            except IOException:
                                # nothing to report
                                pass
            else:
                # read the manifest from the deployable ear/jar/war on the file system
                archive = JarFile(source_file.getAbsolutePath())
                manifest = archive.getManifest()

        return manifest
예제 #17
0
 def execute(self):
     self.channelId = self.params.safeGetIntParam("channelId")
     self.channel = self.channelPageService.getChannel(self.channelId)
     if self.channel == None:
         self.addActionError(u"不能加载频道对象。")
         return self.ERROR
      
     if self.isSystemAdmin() == False and self.isChannelSystemAdmin(self.channel) == False:
         self.addActionError(u"你无权管理本频道。")
         return self.ERROR
     if request.getMethod() == "POST":
         tmpl = self.params.safeGetStringParam("tmpl")
         if tmpl == "" :
             self.channel.setSkin("")
             skin = "template1"
         else:
             self.channel.setSkin(tmpl)
             skin = tmpl
         #选择了样式,需要把样式对应的模块以及页面内容写入到channel中
         headerTemplate = self.getFileContent("/WEB-INF/channel/"+skin+"/Header.ftl")
         footerTemplate = self.getFileContent("/WEB-INF/channel/"+skin+"/Footer.ftl")
         indexPageTemplate = self.getFileContent("/WEB-INF/channel/"+skin+"/Main.ftl")
         cssStyle = self.getFileContent("/css/channel/" + skin + "/common.css")
         cssStyle = cssStyle.replace("background:url(", "background:url(../css/channel/" + skin + "/")
         self.channel.setHeaderTemplate(headerTemplate)
         self.channel.setFooterTemplate(footerTemplate)
         self.channel.setIndexPageTemplate(indexPageTemplate)
         self.channel.setCssStyle(cssStyle)
         self.channelPageService.saveOrUpdateChannel(self.channel)    
         return self.SUCCESS        
     # 查找所有样式
     themeFolder = application.getRealPath("/") + "WEB-INF" + File.separator + "channel" + File.separator
     #print themeFolder
     file = File(themeFolder)
     if file.exists() == True:
         theme_list = []
         fs = file.list()
         for theme in fs:
             fd = File(themeFolder + theme)
             if fd.isDirectory() == True:
                 theme_list.append(theme)            
         if len(theme_list) > 0:
             request.setAttribute("theme_list", theme_list)
             
     request.setAttribute("channel", self.channel)
     return "/WEB-INF/ftl/channel/channel_skins.ftl"
예제 #18
0
 def user_info(self):        
     request.setAttribute("user", self.user)
     self.putSubjectList()
     self.putGradeList()
     self.putUserCategories()
 
     folder = File(application.getRealPath("/images/deficon/"));
     if folder.exists() == False or folder.isDirectory() == False:
         return
     
     icons = []
     for f in folder.listFiles():
         ext = CommonUtil.getFileExtension(f.getName()).lower()
         if "jpg" == ext or "gif" == ext or "png" == ext:
             icons.append("images/deficon/" + f.getName())
     if len(icons) > 0:
         request.setAttribute("icon_list", icons)
예제 #19
0
 def deleteDirectory(self, sPath):
     # 如果sPath不以文件分隔符结尾,自动添加文件分隔符  
     dirFile = File(sPath)
     # 如果dir对应的文件不存在,或者不是一个目录,则退出  
     if dirFile.exists() == False or dirFile.isDirectory() == False:
         return
     # 删除文件夹下的所有文件(包括子目录)
     files = dirFile.listFiles()
     for f in files:
         # 删除子文件
         if f.isFile():
             f.delete()
         else:
             self.deleteDirectory(f.getAbsolutePath())
     #/删除当前目录  
     dirFile.delete()
     dirFile = None
def add_folder(zos, folder_name, base_folder_name):
    f = File(folder_name)
    if not f.exists():
        return
    if f.isDirectory():
        for f2 in f.listFiles():
            add_folder(zos, f2.absolutePath, base_folder_name)
        return
    entry_name = folder_name[len(base_folder_name) + 1:len(folder_name)]
    ze = ZipEntry(entry_name)
    zos.putNextEntry(ze)
    input_stream = FileInputStream(folder_name)
    buffer = zeros(1024, 'b')
    rlen = input_stream.read(buffer)
    while (rlen > 0):
        zos.write(buffer, 0, rlen)
        rlen = input_stream.read(buffer)
    input_stream.close()
    zos.closeEntry()
예제 #21
0
def add_folder(zos, folder_name, base_folder_name):
    f = File(folder_name)
    if not f.exists():
        return
    if f.isDirectory():
        for f2 in f.listFiles():
            add_folder(zos, f2.absolutePath, base_folder_name)
        return
    entry_name = folder_name[len(base_folder_name) + 1:len(folder_name)]
    ze = ZipEntry(entry_name)
    zos.putNextEntry(ze)
    input_stream = FileInputStream(folder_name)
    buffer = zeros(1024, 'b')
    rlen = input_stream.read(buffer)
    while (rlen > 0):
        zos.write(buffer, 0, rlen)
        rlen = input_stream.read(buffer)
    input_stream.close()
    zos.closeEntry()
예제 #22
0
def metaFolders(ppath, chstr):
	dirc = JFile(ppath)
	print dirc
	filesA = dirc.list()
	
	sp = JFile.separator
	filesL = filesA.tolist()
	filesL.sort()
	projsimp = None
	for idx, i in enumerate(filesL):
		path = ppath + sp + i
		pathcheck = JFile(path)
		if pathcheck.isDirectory(): 
			stackimp = importAChannle(path, chstr)
			zpstackimp = maxZprojection(stackimp)
			if projsimp == None:
				projsimp = createStackImp(zpstackimp)
			else:
				projsimp.getStack().addSlice("T" + str(idx), zpstackimp.getProcessor())
			print "--- TimePoint" + str(idx)+ " max Zprojection added ---"
	return projsimp
예제 #23
0
    def _add_nodes(self, curTop, dir):
        """
        Recursive implementation to fill the tree with filenames and directories

        :param curTop: current top directory
        :param dir: next directory
        :return: None
        """
        curPath = dir.getPath()
        if os.path.isdir(curPath):
            nodePath = os.path.basename(curPath)
        curDir = DefaultMutableTreeNode(nodePath)
        if curTop != None:  # should only be null at root
            curTop.add(curDir)
        ol = Vector()
        tmp = dir.list()
        for i in xrange(0, len(tmp)):
            ol.addElement(tmp[i])
        thisObject = None
        files = Vector()
        # Make two passes, one for Dirs and one for Files. This is #1.
        for i in xrange(0, ol.size()):
            thisObject = ol.elementAt(i)
            if curPath == self._dir:
                newPath = thisObject
            else:
                newPath = os.path.join(curPath, thisObject)
            f = File(newPath)
            if f.isDirectory():
                self._add_nodes(curDir, f)
            else:
                files.addElement(thisObject)

        # Pass two: for files.
        Collections.sort(files)
        for i in xrange(0, files.size()):
            f = files.elementAt(i)
            #if f.split('.')[-1] != 'html':
            curDir.add(DefaultMutableTreeNode(files.elementAt(i)))
        return curDir
예제 #24
0
    def execute(self):
        if self.loginUser == None:
            return self.LOGIN
        self.unit = self.getUnit()
        if self.unit == None:
            self.addActionError(u"您所访问的机构不存在!")
            return self.ERROR
        if self.isUnitAdmin() == False:
            self.addActionError(u"你没有管理的权限。")
            return self.ERROR

        if request.getMethod() == "POST":
            tmpl = self.params.safeGetStringParam("tmpl")
            if tmpl == "":
                self.unit.setThemeName(None)
            else:
                self.unit.setThemeName(tmpl)
            self.unitService.saveOrUpdateUnit(self.unit)
            fc = FileCache()
            fc.deleteUnitCacheFile(self.unit.unitName)
            fc = None
            return self.SUCCESS

        # 查找所有样式
        themeFolder = application.getRealPath(
            "/") + "theme" + File.separator + "units" + File.separator
        file = File(themeFolder)
        if file.exists() == True:
            theme_list = []
            fs = file.list()
            for theme in fs:
                fd = File(themeFolder + theme)
                if fd.isDirectory() == True:
                    theme_list.append(theme)
            if len(theme_list) > 0:
                request.setAttribute("theme_list", theme_list)

        request.setAttribute("unit", self.unit)
        return "/WEB-INF/unitsmanage/unit_skin.ftl"
예제 #25
0
 def import_theme(self):
     servlet_ctxt = self.theme_svc.getServletContext()
     filePath = servlet_ctxt.getRealPath(
         "/") + "theme" + File.separator + "site" + File.separator
     file = File(filePath)
     num = 0
     if file.exists() == True:
         fs = file.list()
         num = 0
         for f in fs:
             fd = File(filePath + f)
             if fd.isDirectory() == True:
                 theme = self.theme_svc.getSiteThemeByFolderName(f)
                 if theme == None:
                     theme = SiteTheme()
                     theme.setTitle(f)
                     theme.setFolder(f)
                     theme.setStatus(0)
                     self.theme_svc.saveOrUpdateSiteTheme(theme)
                     num = num + 1
     retMsg = str(num)
     request.setAttribute("retMsg", retMsg)
     return "/WEB-INF/ftl/admin/site_theme.ftl"
예제 #26
0
    def deleteDirectory(self, sPath):
        # 如果sPath不以文件分隔符结尾,自动添加文件分隔符
        dirFile = File(sPath)
        # 如果dir对应的文件不存在,或者不是一个目录,则退出
        if dirFile.exists() == False or dirFile.isDirectory() == False:
            return

        FileUtils.deleteQuietly(dirFile)
        return
        """
        换一种新的方法,以下代码不用了
        """
        # 删除文件夹下的所有文件(包括子目录)
        files = dirFile.listFiles()
        if files == None or len(files) == 0: return
        for f in files:
            # 删除子文件
            if f.isFile():
                f.delete()
            else:
                self.deleteDirectory(f.getAbsolutePath())
        #/删除当前目录
        dirFile.delete()
        dirFile = None
예제 #27
0
class CommandHeap(Commands):
    def __init__(self):
        pass
    
    def buildCommands(self,s):
        self.path=File(s)
        files=[]
        if self.path.isDirectory(): self.addCommands(self.path, files)
        self.heap=Heap(files)
    
    def addCommands(self, path, files):
        commands = path.listFiles()
        for x in commands:
            if x.isDirectory(): self.addCommands(x,files)
            else: files.append(x)
    
    def exists(self,command):
        return self.heap.exists(command)
    
    def update(self):
        self.buildCommands(self.path.getName())
    
    def getAllCommands(self):
        return self.heap.getAll()
예제 #28
0
    def _configure_classpath(self):
        """
        jboss CLI does something dodgy and can't just append the cli.jar to the system path
        sys.path.append(jboss_home + "/bin/client/jboss-cli-client.jar")
        instead we are going to add a URL classloader into the loader hierarchy of
        the current thread context
        """
        jboss_home_str = normalize_dirpath(self.get_jboss_home())
        jboss_home = File(jboss_home_str)
        if not jboss_home.isDirectory():
            raise ContextError("jboss_home %s is not a directory or does not exist" % jboss_home_str)

        # should work but does not
        # sys.path.insert(0, os.path.join(jboss_home_str, 'bin', 'client', 'jboss-cli-client.jar'))
        # sys.path.insert(0, os.path.join(jboss_home_str, 'jboss-modules.jar'))

        jars = array([], URL)
        jars.append(File(os.path.join(jboss_home_str, 'bin', 'client', 'jboss-cli-client.jar')).toURL())
        jars.append(File(os.path.join(jboss_home_str, 'jboss-modules.jar')).toURL())
        current_thread_classloader = Thread.currentThread().getContextClassLoader()
        Thread.currentThread().setContextClassLoader(URLClassLoader(jars, current_thread_classloader))

        debug('Added jboss client jars from %s to context class loader' % jboss_home_str)
        self._jboss_home_classpath = jboss_home_str
예제 #29
0
 def uploadToAWS(self):
     from java.io import File
     import os
     logger.info("start to s3sync hive database [{}]", self.database_name)
     # self.s3_helper.list(self.aws_s3_path)
     # self.s3_helper.sync(self.local_staging_dir, self.aws_s3_path)
     staging_dir = File(self.local_staging_dir)
     table_dirs = [
         dir for dir in staging_dir.list() if staging_dir.isDirectory()
     ]
     table_count = len(table_dirs)
     logger.info("There were [{}] sub directories under [{}]: ",
                 table_count, self.local_staging_dir, ", ".join(table_dirs))
     for idx, table_dir in enumerate(table_dirs):
         _stopwatch = Stopwatch()
         sub_staging_dir = "{local_staging_dir}/{table_dir}".format(
             local_staging_dir=self.local_staging_dir, table_dir=table_dir)
         sub_aws_s3_path = "{aws_s3_path}/{table_dir}".format(
             aws_s3_path=self.aws_s3_path, table_dir=table_dir)
         indicator = "===> [{cur}/{total}] ".format(cur=(idx + 1),
                                                    total=table_count)
         logger.info(
             "{} - Start to s3sync table [{}] for hive database [{}]",
             indicator, table_dir, self.database_name)
         rc = self.s3_helper.sync(sub_staging_dir, sub_aws_s3_path)
         _stopwatch.stop()
         if rc == 0:
             logger.info(
                 "{} - End s3sync table [{}] for hive database [{}] successfully, elapse time - {}",
                 indicator, table_dir, self.database_name, str(_stopwatch))
         else:
             logger.error(
                 "{} - End s3sync table [{}] for hive database [{}], but error occurred, elapse time - {}",
                 indicator, table_dir, self.database_name, str(_stopwatch))
     self.s3_helper.list(self.aws_s3_path)
     logger.info("End uploading hive database [{}]", self.database_name)
예제 #30
0
from java.nio.file import Paths
from java.nio.file import Path
from java.io import File

p=Paths.get("home","pi","Desktop","jython-prac-prog","stram_jython","file2.txt")

x = p.toFile()

x = File(x.getName())
print (x.isFile())

f = File("image1.png") 
print (f.getName())
print ("length",f.length())
print ("Execute",f.canExecute())
print ("read",f.canRead())
print ("write",f.canWrite())
print ("path",f.getPath())
print ("Directory",f.isDirectory())
print ("parent",f.getParent())

예제 #31
0
from java.io import File
import os

co = raw_input("enter directory: ")
print (co)


f_d = File(co)
print ("process:")
if(f_d.exists()):
   if(f_d.isDirectory()):
	os.chdir(co) #must use otherwise you got all containts as directory
	for k in f_d.list():
		if os.path.isfile(k):
			print (k+"  - file")
		else:
			print (k+"  - directory")
		
   else:
	print ("not directory")
else:
	print ("not exist")


print ("end:")