本文整理匯總了Python中Files類的典型用法代碼示例。如果您正苦於以下問題:Python Files類的具體用法?Python Files怎麽用?Python Files使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Files類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
def __init__(self, group):
self.group = group #Which Searcher this is
self.fileName = Files.getFileName(Files.join(self.searchesFolder, "Group"+group.groupID))
#Will only be set on load. This is the groupID of the parent group
self.parentID = None #(stored because many groups we save messages for groups that no longer exist on GroupMe)
self._messageList = [] #This contains all known messages in chronological order. Values should all be standard strings
self._hasLoaded = False
示例2: loadGroup
def loadGroup(folder):
if type(folder) == int:
folder = "Group "+str(folder)
try:
loadedGroup = _folderCache[folder]
log.group("Group already loaded, returning group:", loadedGroup)
return loadedGroup
except KeyError:
pass #Just continue loading
try:
groupNumber = int(re.search("\d+", folder).group())
log.group("Loading Group:", groupNumber)
except AttributeError:
raise RuntimeError("Group Folder '"+folder+"' does not have a group number")
try:
with open(Files.getFileName(Files.join(folder, SAVE_FILE_NAME))) as file:
groupType = Files.read(file)
log.group("Group Type:",groupType)
newGroup = globals()[groupType](groupNumber).load(file) #Load arbitrary class
_folderCache[folder] = newGroup #Save it to a cache so we cannot load twice
return newGroup
#except (KeyError, TypeError, AttributeError) as Error: #I actually think I want this to be a halting error.
# log.error("Failed to properly load group file:", Error)
except FileNotFoundError: #The group was improperly initialized/saved
log.group.error("Group had no load file. Deleting folder")
Files.deleteFolder(folder)
示例3: _filesGetFromPath
def _filesGetFromPath(self,path):
if str(self.current_text).lower().startswith("#files"):
if os.path.isdir(path):
stuff = Files.getFilesFromPath(path)
elif path=="HOME":
home=os.path.expanduser("~")
stuff= Files.getFilesFromPath(home)
else:
stuff=[]
self.webview.page().mainFrame().evaluateJavaScript("setNewFiles({})".format(stuff))
示例4: _save
def _save(self, locationOverride = None):
location = locationOverride if locationOverride is not None else self.fileName
if self._hasLoaded: #If hasn't loaded, nothing has changed yet (can't, hasn't been loaded)
log.save.low("Saving",self)
with Files.SafeOpen(location, "w") as file:
try:
Files.write(file, self.group.parent.groupID)
except AttributeError:
Files.write(file, "0") #In any case where there is no parent
#Then write all messages
json.dump(self._messageList, file)
示例5: sendMessage
def sendMessage( receiver, subject, content, attachments=None, withSMS=None ):
""" 쪽지함에 쪽지를 발송
"""
#[TODO] To,CC,BCC에 대한 처리 필요
#[TODO] IF not logined !!
smsList = []
msgIDXs = []
msgSave = { "Subject": subject, "Content": content, "Sender": Login.getID(), "SenderName": Login.getName() }
if "<" in receiver:
#ex) Address Parsing :: "정기영" <[email protected]>, "김태희" <[email protected]> -> ["[email protected]", "[email protected]"]
addrsList = re.findall("\<([._,a-zA-Z0-9:\#\@]+)\>+", receiver)
else:
addrsList = [n.strip() for n in receiver.split(",")]
for recID in addrsList:
userData = Archive("User").getValues( "User.UserID == "+ recID, "Name,HandPhone" )
if userData:
msgSave["Receiver"] = recID
result_IDX = Archive("MsgInBox").New(**msgSave)
if result_IDX:
msgIDXs.append( result_IDX )
if userData["HandPhone"] and not userData["HandPhone"].replace("-","") in smsList:
smsList.append( str(userData["HandPhone"].replace("-","")) )
sentMsg = { "RelateIDX": result_IDX, "Subject": subject, "Content": content, "Receiver": recID, "ReceiverName": userData["Name"], "Sender": Login.getID() }
r = Archive("MsgSent").New( **sentMsg )
if attachments:
#[TODO] 임시 코드입니다. 멀티센딩에서 업된 파일에 대한 레퍼런스 카운트가 이상적이나 일단 그냥 복제형태로 갑니다.
if type(attachments) == unicode:
attachments = attachments.encode("utf8")
uploadFile = Files.getRootDir() + attachments
fileName = os.path.split(attachments)[1]
if os.path.exists( uploadFile ):
for ridx in msgIDXs:
if str(ridx).isdigit():
targetFile = "/data/message/%s.%s" % ( fileName, ridx )
shutil.copy2( uploadFile, Files.getSpartaDir() + targetFile )
msgMod = { "IDX" : ridx, "Attachments" : "%s" % fileName }
r = Archive( "MsgInBox" ).New( **msgMod )
os.remove(uploadFile)
if withSMS and smsList:
SMS.send( sendMsg=u"스팔타쪽지>"+msgSave["Subject"], recvList=smsList )
return len(msgIDXs)
示例6: __init__
def __init__(self, group):
#Users will be "verified" when communicating with the server.
#People who do not exist will not usually be sent in requests for group members
self.hasVerified = False
self.group = group #Group reference
self.dirName = Files.join(Files.getGroupFolder(self.group), "Users")
#Note: position in userList is not static
self.userList = [] #This will be where users are normally stored
self.IDDict = {}
self.aliasList = {}
#Creates folder if it does not exist
Files.createFolder(self.dirName)
示例7: main
def main():
"""
Main program function
"""
#Get the arguments
#args=getArgument()
args=Files()
#Initiate graph object
mygraph=Graph()
#If the uniprot2go filter is done
if(args.filter):
#Intanciate a multilist object
mymultilist=Multilist(args.multilist)
#filter data
mymultilist.GOfilter(args.filter,args.results)
#Change multilist file
args.multilist=mymultilist.filtered
#If multilist file is given
if(args.multilist):
config=Davidconfig(args.config)
#Parse multilist data
mygraph.parse(Multilist(args.multilist))
#Parse pValue data
if(args.pValue): mygraph.parse(pValue(args.pValue))
#Parse similarity data
if(args.similarity): mygraph.parse(Similarity(args.similarity))
#Parse interaction data
if(args.interact): mygraph.parse(Interact(args.interact))
if(args.iRNA_db): mygraph.parse(Database_data(args.iRNA_db,args.fastmode))
#Analysis david results from file
if(args.enrichment):
#Get enrichment data
enrichment=config.readconfig(David(args.enrichment))
#Set data on the graph
mygraph.parse(enrichment)
#Analyse multilist with david
elif(args.david):
#Set config data
enrichment=config.readconfig(David())
#Get david data
enrichment.analysis(mygraph)
#Write data
enrichment.writefile(args.results)
#Set data on the graph
mygraph.parse(enrichment)
if(args.name): mygraph.parse(Name(args.name))
#Generate nodes csv
mygraph.writefile(args.results)
示例8: handle_error
def handle_error(self, request, client_address):
Events.getLockObject().release() #Release the lock we have on message processing
stringBuffer = io.StringIO()
traceback.print_exc(file = stringBuffer)
stringBuffer.seek(0) #Reset to start of message
errorMessage = stringBuffer.read().replace("\n","\r\n")
log.error("==== ERROR OCCURRED IN SERVER. PRINTING ERROR ====")
log.error(errorMessage) #Output the message to logging
if SEND_ERRORS_OVER_GROUPME:
sendGroup = makeNamedGroup(99, "23222092", ("27094908", Files.getTokenList()[0]))
sendGroup.setBot("3da109b71b8c3363c4b87a7e67")
sendGroup.save()
try:
if sendGroup:
log.network.statePush(False)
success = sendGroup.handler.write("\nMESSAGE FOR YOU SIR:\n" + errorMessage)
log.network.statePop()
if success:
log.error("Successful error report sent")
else:
log.error("Failed to send error report")
except Exception as e: #I don't care about any errors here. jk
raise e #Jk I do
示例9: ThumbInsert
def ThumbInsert(arg, extra):
idx = extra["idx"]
modifyData = { "IDX": idx, "_pass_":True, "useSpartaDir": True }
# 샷 정보 가져오기
shotData = get( idx, "Shot.Parent1,Shot.Parent2,Project.Code,Seq.TypeCode,Shot.TypeCode,Shot.Thumb")
# 기존 썸네일이 있으면 삭제
oldThumbPath = os.path.join(Files.getRootDir(), shotData["Thumb"][1:])
if os.path.exists(oldThumbPath):
os.unlink(oldThumbPath)
pData = {
"Project.Code": shotData["Project.Code"],
"Seq.TypeCode": shotData["Seq.TypeCode"],
"Shot.TypeCode": shotData["TypeCode"],
"Shot.Code": Naming.ApplyWithQuery("Shot.Code", idx, **arg )
}
if "Thumb" in arg: modifyData["Thumb"] = arg["Thumb"]
Files.CopyThumb2Naming( "Shot.Thumb", idx, inArg=modifyData, preData=pData )
edit( idx, **modifyData )
return arg
示例10: makeAsset2Shot
def makeAsset2Shot(idx, typecode=None, statcode=None ):
""" 선택한 에셋들에 대한 부모 샷을 만들고 서브로 링크 """
cnt = 0
if (type(idx) == str) and "," in idx:
idxList = idx.split(",")
else:
idxList = [idx,]
for nIDX in idxList:
assetData = Archive("Asset").getValues(idx, "Parent1,Name,Thumb,Preview,ScanEdgeCode,ScanDuration")
shotSave = {
"Parent1": assetData["Parent1"],
"Name" : assetData["Name"],
"Thumb": Files.getRootDir() + assetData["Thumb"],
"Preview": assetData["Preview"],
"Duration": assetData["ScanDuration"]
}
if statcode: shotSave["StatCode"] = statcode
if typecode: shotSave["TypeCode"] = typecode
shot_IDX = Archive("Shot").New(**shotSave)
r = Archive("Shot").addLink(shot_IDX, "Asset", idx)
if (r > 0):
cnt += 1
return cnt
示例11: readIPFile
def readIPFile():
_ipFile = Files.getFileName("ip_address")
try:
with open(_ipFile) as file:
return file.read().rstrip()
except FileNotFoundError:
log.info.debug("No ip file")
示例12: DefaultThumbnail
def DefaultThumbnail( arg=None ):
""" 디폴트로 설정된 이미지를 반환하거나 스탬핑 한다 """
defImage = Files.getNoImage()
if ((arg != None) and (type(arg) == dict)) and not ("Thumb" in arg):
arg["Thumb"] = defImage
return defImage
示例13: loadAllUsers
def loadAllUsers(self):
files = Files.getFilesInDir(self.dirName)
log.user("Loading {: 2} users for Group".format(len(files)), self.group.ID)
for userFile in files:
try:
user = User.loadUser(userFile, self.group)
self.addUser(user)
except KeyError: #This means the data was corrupted on save
log.user.error("Could not load user from file:",userFile,"is probably corrupted")
示例14: load
def load(self):
if not self._hasLoaded:
log.save.low("Loading",self)
self._hasLoaded = True
try:
with open(self.fileName, "r") as file:
self.parentID = Files.read(file)
self._messageList = json.load(file)
except FileNotFoundError:
log.save.debug("No file found for",self,", not loading")
except ValueError:
log.save.error("Invalid JSON Saving on server stop")
示例15: __init__
def __init__(self):
QtGui.QMainWindow.__init__(self, None,QtCore.Qt.WindowStaysOnTopHint|QtCore.Qt.FramelessWindowHint)#| QtCore.Qt.X11BypassWindowManagerHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setWindowTitle("ducklauncher")#recognisable by wnck
#screen size
d = QtGui.QDesktopWidget()
self.top_pos=0
self.s_width = d.availableGeometry().width()
self.s_height =d.availableGeometry().height()
d.resized.connect(self.updateSize)
#Config
conf=Config.get()
self.conf=conf
self.HALF_OPEN_POS=int(conf['size'])
self.ICO_TOP=self.HALF_OPEN_POS-5
self.OPEN_STATE_TOP=self.ICO_TOP*4+5
self.SIZE = 15
self.R=int(conf['r'])
self.G=int(conf['g'])
self.B=int(conf['b'])
self.ICON_SIZE=int(conf['icon-size'])
#Geometry
self.setGeometry(0,0,self.HALF_OPEN_POS+4,self.s_height)
#reserve wndow space
#self.activateWindow()
xwin = XlibStuff.fix_window(self.winId(),self.HALF_OPEN_POS+5,0,0,0)
#
#Values
self.apps_per_row = math.trunc(((self.s_width/3)-30)/self.ICON_SIZE)
self.apps_per_col = math.trunc(((self.s_height)-30)/self.ICON_SIZE)
self.apps_per_page=self.apps_per_col*self.apps_per_row
self.app_page_state=0
self.files_page_state=0
self.Files = Files.getFiles()
self.pos_x=self.HALF_OPEN_POS
self.move=False
self.current_state="half_open"
self.activity="apps"
self.dock_apps = Apps.find_info(self.conf['dock-apps'])
self.current_text=''
#Update open windows
self.timer=QtCore.QTimer()
self.timer.setInterval(2000)
self.timer.start()
self.timer.timeout.connect(self.updateOpenWindows)
#
self.open_windows=window.get_open_windows()
self.open_win = window.open_windows()
self.open_state=False
#
self.settings_win = Settings.Window(self)