感谢您的反馈,我们新增加了mac系统的支持。刚刚上传了mac系统的python 3.6版本,您可以重新pip安装使用。mac系统的python 3.7和python 3.5版本支持正在准备中。. Then I also noticed What are 'named tuples' in Python?, which points out that sys.versioninfo is now a namedtuple, so perhaps the Python standard library already came up with this idea much earlier. Note that unfortunately (this still being Python), you can erase the entire Foo assignment altogether: Foo = 'bar' (facepalm).
Earlier I wrote about in Python. This post will be about how to handle those.
Built-in ExceptionsIn Python, all exceptions must be instances of a class that derives from. In a statement with anclause that mentions a particular class, that clause also handles any exceptionclasses derived from that class (but not exception classes from which it isderived). Two exception classes that are not related via subclassing are neverequivalent, even if they have the same name.The built-in exceptions listed below can be generated by the interpreter orbuilt-in functions. Except where mentioned, they have an “associated value”indicating the detailed cause of the error. This may be a string or a tuple ofseveral items of information (e.g., an error code and a string explaining thecode).
The associated value is usually passed as arguments to the exceptionclass’s constructor.User code can raise built-in exceptions. This can be used to test an exceptionhandler or to report an error condition “just like” the situation in which theinterpreter raises the same exception; but beware that there is nothing toprevent user code from raising an inappropriate error.The built-in exception classes can be subclassed to define new exceptions;programmers are encouraged to derive new exceptions from theclass or one of its subclasses, and not from. Moreinformation on defining exceptions is available in the Python Tutorial under.When raising (or re-raising) an exception in an orclausecontext is automatically set to the last exception caught; if thenew exception is not handled the traceback that is eventually displayed willinclude the originating exception(s) and the final exception.When raising a new exception (rather than using a bare raise to re-raisethe exception currently being handled), the implicit exception context can besupplemented with an explicit cause by using with.
Raise newexc from originalexcThe expression following must be an exception or None. Itwill be set as cause on the raised exception. Settingcause also implicitly sets the suppresscontextattribute to True, so that using raise newexc from Noneeffectively replaces the old exception with the new one for displaypurposes (e.g. Converting to ), whileleaving the old exception available in context for introspectionwhen debugging.The default traceback display code shows these chained exceptions inaddition to the traceback for the exception itself. An explicitly chainedexception in cause is always shown when present. An implicitlychained exception in context is shown only if causeis and suppresscontext is false.In either case, the exception itself is always shown after any chainedexceptions so that the final line of the traceback always shows the lastexception that was raised.
Base classesThe following exceptions are used mostly as base classes for other exceptions. Exception BaseExceptionThe base class for all built-in exceptions. It is not meant to be directlyinherited by user-defined classes (for that, use ). Ifis called on an instance of this class, the representation ofthe argument(s) to the instance are returned, or the empty string whenthere were no arguments.
ArgsThe tuple of arguments given to the exception constructor. Some built-inexceptions (like ) expect a certain number of arguments andassign a special meaning to the elements of this tuple, while others areusually called only with a single string giving an error message. Withtraceback ( tb )This method sets tb as the new traceback for the exception and returnsthe exception object. It is usually used in exception handling code likethis.
Except SomeException: tb = sys. Excinfo 2 raise OtherException (. Withtraceback ( tb ) exception ExceptionAll built-in, non-system-exiting exceptions are derived from this class. Alluser-defined exceptions should also be derived from this class.
Exception ArithmeticErrorThe base class for those built-in exceptions that are raised for variousarithmetic errors:,. Exception BufferErrorRaised when a related operation cannot beperformed. Exception LookupErrorThe base class for the exceptions that are raised when a key or index used ona mapping or sequence is invalid:,. Thiscan be raised directly.
Concrete exceptionsThe following exceptions are the exceptions that are usually raised. Exception AssertionErrorRaised when an statement fails. Exception AttributeErrorRaised when an attribute reference (see ) orassignment fails. (When an object does not support attribute references orattribute assignments at all, is raised.) exception EOFErrorRaised when the function hits an end-of-file condition (EOF)without reading any data. (N.B.: the io.IOBase.read andmethods return an empty string when they hit EOF.) exception FloatingPointErrorNot currently used.
Exception GeneratorExitRaised when a or is closed;see. Itdirectly inherits from instead of sinceit is technically not an error. Exception ImportErrorRaised when the statement has troubles trying toload a module. Also raised when the “from list” in from. Importhas a name that cannot be found.The name and path attributes can be set using keyword-onlyarguments to the constructor. When set they represent the name of the modulethat was attempted to be imported and the path to any file which triggeredthe exception, respectively. New in version 3.6.
Exception IndexErrorRaised when a sequence subscript is out of range. (Slice indices aresilently truncated to fall in the allowed range; if an index is not aninteger, is raised.) exception KeyErrorRaised when a mapping (dictionary) key is not found in the set of existing keys. Exception KeyboardInterruptRaised when the user hits the interrupt key (normally Control-C orDelete). During execution, a check for interrupts is maderegularly. The exception inherits from so as to not beaccidentally caught by code that catches and thus preventthe interpreter from exiting. Exception MemoryErrorRaised when an operation runs out of memory but the situation may still berescued (by deleting some objects).
The associated value is a string indicatingwhat kind of (internal) operation ran out of memory. Note that because of theunderlying memory management architecture (C’s malloc function), theinterpreter may not always be able to completely recover from this situation; itnevertheless raises an exception so that a stack traceback can be printed, incase a run-away program was the cause. Exception NameErrorRaised when a local or global name is not found. This applies only tounqualified names. The associated value is an error message that includes thename that could not be found.
Exception NotImplementedErrorThis exception is derived from. In user defined baseclasses, abstract methods should raise this exception when they requirederived classes to override the method, or while the class is beingdeveloped to indicate that the real implementation still needs to be added.
NoteNotImplementedError and NotImplemented are not interchangeable,even though they have similar names and purposes. Seefor details on when to use it. Exception OSError ( arg ) exception OSError ( errno, strerror , filename , winerror , filename2 )This exception is raised when a system function returns a system-relatederror, including I/O failures such as “file not found” or “disk full”(not for illegal argument types or other incidental errors).The second form of the constructor sets the corresponding attributes,described below.
The attributes default to if notspecified. For backwards compatibility, if three arguments are passed,the attribute contains only a 2-tupleof the first two constructor arguments.The constructor often actually returns a subclass of, asdescribed in below. The particular subclass depends onthe final value.
This behaviour only occurs whenconstructing directly or via an alias, and is notinherited when subclassing. ErrnoA numeric error code from the C variable errno. WinerrorUnder Windows, this gives you the nativeWindows error code. The attribute is then an approximatetranslation, in POSIX terms, of that native error code.Under Windows, if the winerror constructor argument is an integer,the attribute is determined from the Windows error code,and the errno argument is ignored. On other platforms, thewinerror argument is ignored, and the attributedoes not exist. StrerrorThe corresponding error message, as provided bythe operating system.
It is formatted by the Cfunctions perror under POSIX, and FormatMessageunder Windows. Filename filename2For exceptions that involve a file system path (such as or), is the file name passed to the function.For functions that involve two file system paths (such as), corresponds to the secondfile name passed to the function. Changed in version 3.4: The attribute is now the original file name passed tothe function, instead of the name encoded to or decoded from thefilesystem encoding. Also, the filename2 constructor argument andattribute was added.
Exception OverflowErrorRaised when the result of an arithmetic operation is too large to berepresented. This cannot occur for integers (which would rather raisethan give up). However, for historical reasons,OverflowError is sometimes raised for integers that are outside a requiredrange. Because of the lack of standardization of floating point exceptionhandling in C, most floating point operations are not checked.
Exception RecursionErrorThis exception is derived from. It is raised when theinterpreter detects that the maximum recursion depth (see) is exceeded. New in version 3.5: Previously, a plain was raised. Exception ReferenceErrorThis exception is raised when a weak reference proxy, created by thefunction, is used to access an attribute of the referentafter it has been garbage collected.
For more information on weak references,see the module. Exception RuntimeErrorRaised when an error is detected that doesn’t fall in any of the othercategories. The associated value is a string indicating what precisely wentwrong. Exception StopIterationRaised by built-in function and an ’smethod to signal that there are no furtheritems produced by the iterator.The exception object has a single attribute value, which isgiven as an argument when constructing the exception, and defaultsto.When a or functionreturns, a new instance israised, and the value returned by the function is used as thevalue parameter to the constructor of the exception.If a generator code directly or indirectly raises,it is converted into a (retaining theas the new exception’s cause).
New in version 3.5. Exception SyntaxErrorRaised when the parser encounters a syntax error. This may occur in anstatement, in a call to the built-in functionsor, or when reading the initial script or standard input(also interactively).Instances of this class have attributes filename, lineno,offset and text for easier access to the details.of the exception instance returns only the message. Exception IndentationErrorBase class for syntax errors related to incorrect indentation. This is asubclass of. Exception TabErrorRaised when indentation contains an inconsistent use of tabs and spaces.This is a subclass of.
Exception SystemErrorRaised when the interpreter finds an internal error, but the situation does notlook so serious to cause it to abandon all hope. The associated value is astring indicating what went wrong (in low-level terms).You should report this to the author or maintainer of your Python interpreter.Be sure to report the version of the Python interpreter ( sys.version; it isalso printed at the start of an interactive Python session), the exact errormessage (the exception’s associated value) and if possible the source of theprogram that triggered the error. Exception SystemExitThis exception is raised by the function. It inherits frominstead of so that it is not accidentallycaught by code that catches. This allows the exception toproperly propagate up and cause the interpreter to exit.
When it is nothandled, the Python interpreter exits; no stack traceback is printed. Theconstructor accepts the same optional argument passed to.If the value is an integer, it specifies the system exit status (passed toC’s exit function); if it is None, the exit status is zero; ifit has another type (such as a string), the object’s value is printed andthe exit status is one.A call to is translated into an exception so that clean-uphandlers ( clauses of statements) can beexecuted, and so that a debugger can execute a script without running the riskof losing control. The function can be used if it isabsolutely positively necessary to exit immediately (for example, in the childprocess after a call to ). CodeThe exit status or error message that is passed to the constructor.(Defaults to None.) exception TypeErrorRaised when an operation or function is applied to an object of inappropriatetype. The associated value is a string giving details about the type mismatch.This exception may be raised by user code to indicate that an attemptedoperation on an object is not supported, and is not meant to be. If an objectis meant to support a given operation but has not yet provided animplementation, is the proper exception to raise.Passing arguments of the wrong type (e.g.
Passing a when anis expected) should result in a, but passingarguments with the wrong value (e.g. A number outside expected boundaries)should result in a. Exception UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, butno value has been bound to that variable.
This is a subclass of. Exception UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs. It is asubclass of.has attributes that describe the encoding or decodingerror. For example, err.objecterr.start:err.end gives the particularinvalid input that the codec failed on. EncodingThe name of the encoding that raised the error. ReasonA string describing the specific codec error.
ObjectThe object the codec was attempting to encode or decode. StartThe first index of invalid data in.
EndThe index after the last invalid data in. Exception UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding. It is a subclass of. Exception UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding. It is a subclass of. Exception UnicodeTranslateErrorRaised when a Unicode-related error occurs during translating.
It is a subclassof. Exception ValueErrorRaised when an operation or function receives an argument that has theright type but an inappropriate value, and the situation is not described by amore precise exception such as.
Exception ZeroDivisionErrorRaised when the second argument of a division or modulo operation is zero. Theassociated value is a string indicating the type of the operands and theoperation.The following exceptions are kept for compatibility with previous versions;starting from Python 3.3, they are aliases of. Exception EnvironmentError exception IOError exception WindowsErrorOnly available on Windows.
OS exceptionsThe following exceptions are subclasses of, they get raiseddepending on the system error code. Exception BlockingIOErrorRaised when an operation would block on an object (e.g. Socket) setfor non-blocking operation.Corresponds to errno EAGAIN, EALREADY,EWOULDBLOCK and EINPROGRESS.In addition to those of, can haveone more attribute: characterswrittenAn integer containing the number of characters written to the streambefore it blocked. This attribute is available when using thebuffered I/O classes from the module.
Exception ChildProcessErrorRaised when an operation on a child process failed.Corresponds to errno ECHILD. Exception ConnectionErrorA base class for connection-related issues.Subclasses are,and.
Exception BrokenPipeErrorA subclass of, raised when trying to write on apipe while the other end has been closed, or trying to write on a socketwhich has been shutdown for writing.Corresponds to errno EPIPE and ESHUTDOWN. Exception ConnectionAbortedErrorA subclass of, raised when a connection attemptis aborted by the peer.Corresponds to errno ECONNABORTED. Exception ConnectionRefusedErrorA subclass of, raised when a connection attemptis refused by the peer.Corresponds to errno ECONNREFUSED. Exception ConnectionResetErrorA subclass of, raised when a connection isreset by the peer.Corresponds to errno ECONNRESET. Exception FileExistsErrorRaised when trying to create a file or directory which already exists.Corresponds to errno EEXIST.
Exception FileNotFoundErrorRaised when a file or directory is requested but doesn’t exist.Corresponds to errno ENOENT. Exception InterruptedErrorRaised when a system call is interrupted by an incoming signal.Corresponds to errno. Changed in version 3.5: Python now retries system calls when a syscall is interrupted by asignal, except if the signal handler raises an exception (seefor the rationale), instead of raising.
Exception IsADirectoryErrorRaised when a file operation (such as ) is requestedon a directory.Corresponds to errno EISDIR. Exception NotADirectoryErrorRaised when a directory operation (such as ) is requestedon something which is not a directory.Corresponds to errno ENOTDIR. Exception PermissionErrorRaised when trying to run an operation without the adequate accessrights - for example filesystem permissions.Corresponds to errno EACCES and EPERM. Exception ProcessLookupErrorRaised when a given process doesn’t exist.Corresponds to errno ESRCH. Exception TimeoutErrorRaised when a system function timed out at the system level.Corresponds to errno ETIMEDOUT. WarningsThe following exceptions are used as warning categories; see thedocumentation for more details.
Exception WarningBase class for warning categories. Exception UserWarningBase class for warnings generated by user code. Exception DeprecationWarningBase class for warnings about deprecated features when those warnings areintended for other Python developers. Exception PendingDeprecationWarningBase class for warnings about features which are obsolete andexpected to be deprecated in the future, but are not deprecatedat the moment.This class is rarely used as emitting a warning about a possibleupcoming deprecation is unusual, andis preferred for already active deprecations. Exception SyntaxWarningBase class for warnings about dubious syntax. Exception RuntimeWarningBase class for warnings about dubious runtime behavior.
Exception FutureWarningBase class for warnings about deprecated features when those warnings areintended for end users of applications that are written in Python. Exception ImportWarningBase class for warnings about probable mistakes in module imports. Exception UnicodeWarningBase class for warnings related to Unicode. Exception BytesWarningBase class for warnings related to. Exception ResourceWarningBase class for warnings related to resource usage. Ignored by the defaultwarning filters.