本文整理汇总了Python中tools.exit函数的典型用法代码示例。如果您正苦于以下问题:Python exit函数的具体用法?Python exit怎么用?Python exit使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了exit函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: printList
def printList(listItems, title="", showSelector=False,
showByStep=20, showUrl=False):
if title:
separator("=", title)
total = len(listItems)
printLine("Total found: %d" % total)
for key, item in enumerate(listItems):
key += 1
printLine("%s : %s%s%s" % (
str(key).rjust(3, " "),
printDate(item.created).ljust(12, " ") if hasattr(item, 'created') else '',
item.title if hasattr(item, 'title') else item.name,
" " + (">>> " + config.NOTE_URL % item.guid) if showUrl else '',))
if key % showByStep == 0 and key < total:
printLine("-- More --", "\r")
tools.getch()
printLine(" " * 12, "\r")
if showSelector:
printLine(" 0 : -Cancel-")
try:
while True:
num = rawInput(": ")
if tools.checkIsInt(num) and 1 <= int(num) <= total:
return listItems[int(num) - 1]
if num == '0':
exit(1)
failureMessage('Incorrect number "%s", '
'please try again:\n' % num)
except (KeyboardInterrupt, SystemExit):
tools.exit()
开发者ID:MarioRicalde,项目名称:geeknote,代码行数:35,代码来源:out.py
示例2: wrapper
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception, e:
logging.error("Error: %s : %s", func.__name__, str(e))
if not hasattr(e, 'errorCode'):
out.failureMessage("Sorry, operation has failed!!!.")
tools.exit()
errorCode = int(e.errorCode)
# auth-token error, re-auth
if errorCode == 9:
storage = Storage()
storage.removeUser()
GeekNote()
return func(*args, **kwargs)
elif errorCode == 3:
out.failureMessage("Sorry, you do not have permissions to do this operation.")
else:
return False
tools.exit()
开发者ID:jetgeng,项目名称:geeknote,代码行数:26,代码来源:geeknote.py
示例3: GetUserAuthCode
def GetUserAuthCode():
"""Prompts the user for a two factor auth code."""
try:
code = None
if code is None:
code = rawInput("Two-Factor Authentication Code: ")
except (KeyboardInterrupt, SystemExit):
tools.exit()
return code
开发者ID:Wi1d,项目名称:geeknote,代码行数:10,代码来源:out.py
示例4: login
def login(self):
if self.getEvernote().checkAuth():
out.successMessage("You have already logged in.")
return tools.exit()
if self.getEvernote().auth():
out.successMessage("You have successfully logged in.")
else:
out.failureMessage("Login error.")
return tools.exit()
开发者ID:jetgeng,项目名称:geeknote,代码行数:10,代码来源:geeknote.py
示例5: allowAccess
def allowAccess(self):
response = self.loadPage(self.url['base'],
self.url['access'],
"GET",
{'oauth_token': self.tmpOAuthToken})
logging.debug(response.data)
tree = html.fromstring(response.data);
token = "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[0]}) + "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[1]})
sourcePage = tree.xpath("//input[@name='_sourcePage']/@value")[0]
fp = tree.xpath("//input[@name='__fp']/@value")[0]
targetUrl = tree.xpath("//input[@name='targetUrl']/@value")[0]
logging.debug(token);
if response.status != 200:
logging.error("Unexpected response status "
"on login 200 != %s", response.status)
tools.exitErr()
if 'JSESSIONID' not in self.cookies:
logging.error("Not found value JSESSIONID in the response cookies")
tools.exitErr()
access = self.postData['access']
access['oauth_token'] = self.tmpOAuthToken
access['oauth_callback'] = ""
access['embed'] = 'false'
access['suggestedNotebookName'] = 'Geeknote'
access['supportLinkedSandbox'] = ''
access['analyticsLoginOrigin'] = 'Other'
access['clipperFlow'] = 'false'
access['showSwitchService'] = 'true'
access['_sourcePage'] = sourcePage
access['__fp'] = fp
access['targetUrl'] = targetUrl
response = self.loadPage(self.url['base'],
self.url['access'],
"POST", access, token)
if response.status != 302:
logging.error("Unexpected response status on allowing "
"access 302 != %s", response.status)
logging.error(response.data)
tools.exitErr()
responseData = self.parseResponse(response.location)
if not responseData.has_key('oauth_verifier'):
logging.error("OAuth verifier not found")
tools.exit()
self.verifierToken = responseData['oauth_verifier']
logging.debug("OAuth verifier token take")
开发者ID:dalejung,项目名称:geeknote,代码行数:54,代码来源:oauth.py
示例6: confirm
def confirm(message):
printLine(message)
try:
while True:
answer = rawInput("Yes/No: ")
if answer.lower() in ["yes", "ye", "y"]:
return True
if answer.lower() in ["no", "n"]:
return False
failureMessage('Incorrect answer "%s", ' "please try again:\n" % answer)
except (KeyboardInterrupt, SystemExit):
tools.exit()
开发者ID:Wi1d,项目名称:geeknote,代码行数:12,代码来源:out.py
示例7: logout
def logout(self, force=None):
if not self.getEvernote().checkAuth():
out.successMessage("You have already logged out.")
return tools.exit()
if not force and not out.confirm('Are you sure you want to logout?'):
return tools.exit()
result = self.getEvernote().removeUser()
if result:
out.successMessage("You have successfully logged out.")
else:
out.failureMessage("Logout error.")
return tools.exit()
开发者ID:jetgeng,项目名称:geeknote,代码行数:14,代码来源:geeknote.py
示例8: GetUserCredentials
def GetUserCredentials():
"""Prompts the user for a username and password."""
try:
login = None
password = None
if login is None:
login = rawInput("Login: ")
if password is None:
password = rawInput("Password: ", True)
except (KeyboardInterrupt, SystemExit):
tools.exit()
return (login, password)
开发者ID:nekolyanich,项目名称:geeknote,代码行数:14,代码来源:out.py
示例9: getOAuthToken
def getOAuthToken(self):
response = self.loadPage(self.url['base'], self.url['token'], "GET",
self.getTokenRequestData(oauth_token=self.tmpOAuthToken, oauth_verifier=self.verifierToken))
if response.status != 200:
logging.error("Unexpected response status on getting oauth token 200 != %s", response.status)
tools.exit()
responseData = self.parseResponse(response.data)
if not responseData.has_key('oauth_token'):
logging.error("OAuth token not found")
tools.exit()
logging.debug("OAuth token take : %s", responseData['oauth_token'])
self.OAuthToken = responseData['oauth_token']
开发者ID:KNightWeng,项目名称:ENConsole,代码行数:15,代码来源:oauth.py
示例10: GetUserAuthCode
def GetUserAuthCode():
"""Prompts the user for a two factor auth code."""
creds = _getCredentialsFromFile()
if creds is not None:
return creds[2]
try:
code = None
if code is None:
code = rawInput("Two-Factor Authentication Code: ")
except (KeyboardInterrupt, SystemExit), e:
if e.message:
tools.exit(e.message)
else:
tools.exit
开发者ID:jaguarondi,项目名称:geeknote,代码行数:15,代码来源:out.py
示例11: textToENML
def textToENML(content, raise_ex=False, format='markdown'):
"""
Create an ENML format of note.
"""
if not isinstance(content, str):
content = ""
try:
content = unicode(content, "utf-8")
# add 2 space before new line in paragraph for cteating br tags
content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1 \n\3', content)
if format=='markdown':
contentHTML = markdown.markdown(content).encode("utf-8")
# remove all new-lines characters in html
contentHTML = re.sub(r'\n', r'', contentHTML)
else:
contentHTML = HTMLEscape(content)
return wrapENML(contentHTML)
except:
if raise_ex:
raise Exception("Error while parsing text to html."
" Content must be an UTF-8 encode.")
logging.error("Error while parsing text to html. "
"Content must be an UTF-8 encode.")
out.failureMessage("Error while parsing text to html. "
"Content must be an UTF-8 encode.")
return tools.exit()
开发者ID:gregf,项目名称:geeknote,代码行数:27,代码来源:editor.py
示例12: _searchNote
def _searchNote(self, note):
note = tools.strip(note)
# load search result
result = self.getStorage().getSearch()
if result and tools.checkIsInt(note) and 1 <= int(note) <= len(result.notes):
note = result.notes[int(note)-1]
else:
request = self._createSearchRequest(search=note)
logging.debug("Search notes: %s" % request)
result = self.getEvernote().findNotes(request, 20)
logging.debug("Search notes result: %s" % str(result))
if result.totalNotes == 0:
out.successMessage("Notes have not been found.")
return tools.exit()
elif result.totalNotes == 1 or self.selectFirstOnUpdate:
note = result.notes[0]
else:
logging.debug("Choose notes: %s" % str(result.notes))
note = out.SelectSearchResult(result.notes)
logging.debug("Selected note: %s" % str(note))
return note
开发者ID:jetgeng,项目名称:geeknote,代码行数:28,代码来源:geeknote.py
示例13: getTmpOAuthToken
def getTmpOAuthToken(self):
response = self.loadPage(self.url['base'], self.url['token'], "GET",
self.getTokenRequestData(oauth_callback="https://"+self.url['base']))
if response.status != 200:
logging.error("Unexpected response status on get temporary oauth_token 200 != %s", response.status)
tools.exit()
responseData = self.parseResponse(response.data)
if not responseData.has_key('oauth_token'):
logging.error("OAuth temporary not found")
tools.exit()
self.tmpOAuthToken = responseData['oauth_token']
logging.debug("Temporary OAuth token : %s", self.tmpOAuthToken)
开发者ID:KNightWeng,项目名称:ENConsole,代码行数:16,代码来源:oauth.py
示例14: _createSearchRequest
def _createSearchRequest(self, search=None, tags=None, notebooks=None, date=None, exact_entry=None, content_search=None):
request = ""
if notebooks:
for notebook in tools.strip(notebooks.split(',')):
if notebook.startswith('-'):
request += '-notebook:"%s" ' % tools.strip(notebook[1:])
else:
request += 'notebook:"%s" ' % tools.strip(notebook)
if tags:
for tag in tools.strip(tags.split(',')):
if tag.startswith('-'):
request +='-tag:"%s" ' % tag[1:]
else:
request +='tag:"%s" ' % tag
if date:
date = tools.strip(date.split('-'))
try:
dateStruct = time.strptime(date[0]+" 00:00:00", "%d.%m.%Y %H:%M:%S")
request +='created:%s ' % time.strftime("%Y%m%d", time.localtime(time.mktime(dateStruct)))
if len(date) == 2:
dateStruct = time.strptime(date[1]+" 00:00:00", "%d.%m.%Y %H:%M:%S")
request += '-created:%s ' % time.strftime("%Y%m%d", time.localtime(time.mktime(dateStruct)+60*60*24))
except ValueError, e:
out.failureMessage('Incorrect date format in --date attribute. Format: %s' % time.strftime("%d.%m.%Y", time.strptime('19991231', "%Y%m%d")))
return tools.exit()
开发者ID:jetgeng,项目名称:geeknote,代码行数:29,代码来源:geeknote.py
示例15: textToENML
def textToENML(content, raise_ex=False, format='markdown'):
"""
Create an ENML format of note.
"""
if not isinstance(content, str):
content = ""
try:
content = unicode(content, "utf-8")
# add 2 space before new line in paragraph for creating br tags
content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1 \n\3', content)
if format=='markdown':
contentHTML = markdown.markdown(content).encode("utf-8")
# Non-Pretty HTML output
contentHTML = str(BeautifulSoup(contentHTML))
else:
contentHTML = Editor.HTMLEscape(content)
return Editor.wrapENML(contentHTML)
except:
if raise_ex:
raise Exception("Error while parsing text to html."
" Content must be an UTF-8 encode.")
logging.error("Error while parsing text to html. "
"Content must be an UTF-8 encode.")
out.failureMessage("Error while parsing text to html. "
"Content must be an UTF-8 encode.")
return tools.exit()
开发者ID:Noreaster76,项目名称:geeknote,代码行数:27,代码来源:editor.py
示例16: checkVersion
def checkVersion(self):
versionOK = self.getUserStore().checkVersion("Python EDAMTest",
UserStoreConstants.EDAM_VERSION_MAJOR,
UserStoreConstants.EDAM_VERSION_MINOR)
if not versionOK:
logging.error("Old EDAM version")
return tools.exit()
开发者ID:jetgeng,项目名称:geeknote,代码行数:7,代码来源:geeknote.py
示例17: loadPage
def loadPage(self, url, uri=None, method="GET", params=""):
if not url:
logging.error("Request URL undefined")
tools.exit()
if not uri:
urlData = urlparse(url)
url = urlData.netloc
uri = urlData.path + '?' + urlData.query
# prepare params, append to uri
if params:
params = urlencode(params)
if method == "GET":
uri += ('?' if uri.find('?') == -1 else '&') + params
params = ""
# insert local cookies in request
headers = {
"Cookie": '; '.join([key + '=' + self.cookies[key] for key in self.cookies.keys()])
}
if method == "POST":
headers["Content-type"] = "application/x-www-form-urlencoded"
logging.debug("Request URL: %s:/%s > %s # %s", url,
uri, unquote(params), headers["Cookie"])
conn = httplib.HTTPSConnection(url)
conn.request(method, uri, params, headers)
response = conn.getresponse()
data = response.read()
conn.close()
logging.debug("Response : %s > %s",
response.status,
response.getheaders())
result = tools.Struct(status=response.status,
location=response.getheader('location', None),
data=data)
# update local cookies
sk = Cookie.SimpleCookie(response.getheader("Set-Cookie", ""))
for key in sk:
self.cookies[key] = sk[key].value
return result
开发者ID:d1ffuz0r,项目名称:geeknote,代码行数:47,代码来源:oauth.py
示例18: handleTwoFactor
def handleTwoFactor(self):
self.code = out.GetUserAuthCode()
self.postData['tfa']['code'] = self.code
response = self.loadPage(self.url['base'], self.url['tfa']+";jsessionid="+self.cookies['JSESSIONID'], "POST", self.postData['tfa'])
if not response.location and response.status == 200:
if self.incorrectCode < 3:
out.preloader.stop()
out.printLine('Sorry, incorrect two factor code')
out.preloader.setMessage('Authorize...')
self.incorrectCode += 1
return self.handleTwoFactor()
else:
logging.error("Incorrect two factor code")
if not response.location:
logging.error("Target URL was not found in the response on login")
tools.exit()
开发者ID:MarioRicalde,项目名称:geeknote,代码行数:17,代码来源:oauth.py
示例19: allowAccess
def allowAccess(self):
self.postData['access']['oauth_token'] = self.tmpOAuthToken
self.postData['access']['oauth_callback'] = "https://"+self.url['base']
response = self.loadPage(self.url['base'], self.url['access'], "POST", self.postData['access'])
if response.status != 302:
logging.error("Unexpected response status on allowing access 302 != %s", response.status)
tools.exit()
responseData = self.parseResponse(response.location)
if not responseData.has_key('oauth_verifier'):
logging.error("OAuth verifier not found")
tools.exit()
self.verifierToken = responseData['oauth_verifier']
logging.debug("OAuth verifier token take")
开发者ID:KNightWeng,项目名称:ENConsole,代码行数:18,代码来源:oauth.py
示例20: modifyArgsByStdinStream
def modifyArgsByStdinStream():
content = sys.stdin.read()
content = tools.stdinEncode(content)
if not content:
out.failureMessage("Input stream is empty.")
return tools.exit()
title = " ".join(content.split(" ", 5)[:-1])
title = re.sub(r"(\r\n|\r|\n)", r" ", title)
if not title:
out.failureMessage("Error while crating title of note from stream.")
return tools.exit()
elif len(title) > 50:
title = title[0:50] + "..."
ARGS = {"title": title, "content": content}
return ("create", ARGS)
开发者ID:cleygraf,项目名称:geeknote,代码行数:19,代码来源:geeknote.py
注:本文中的tools.exit函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论