doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
monthdays2calendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers. | python.library.calendar#calendar.Calendar.monthdays2calendar |
monthdayscalendar(year, month)
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers. | python.library.calendar#calendar.Calendar.monthdayscalendar |
yeardatescalendar(year, width=3)
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects. | python.library.calendar#calendar.Calendar.yeardatescalendar |
yeardays2calendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero. | python.library.calendar#calendar.Calendar.yeardays2calendar |
yeardayscalendar(year, width=3)
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero. | python.library.calendar#calendar.Calendar.yeardayscalendar |
calendar.day_abbr
An array that represents the abbreviated days of the week in the current locale. | python.library.calendar#calendar.day_abbr |
calendar.day_name
An array that represents the days of the week in the current locale. | python.library.calendar#calendar.day_name |
calendar.firstweekday()
Returns the current setting for the weekday to start each week. | python.library.calendar#calendar.firstweekday |
class calendar.HTMLCalendar(firstweekday=0)
This class can be used to generate HTML calendars. HTMLCalendar instances have the following methods:
formatmonth(theyear, themonth, withyear=True)
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.
formatyear(theyear, width=3)
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.
formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).
HTMLCalendar has the following attributes you can override to customize the CSS classes used by the calendar:
cssclasses
A list of CSS classes used for each weekday. The default class list is: cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
more styles can be added for each day: cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
Note that the length of this list must be seven items.
cssclass_noday
The CSS class for a weekday occurring in the previous or coming month. New in version 3.7.
cssclasses_weekday_head
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses. New in version 3.7.
cssclass_month_head
The month’s head CSS class (used by formatmonthname()). The default value is "month". New in version 3.7.
cssclass_month
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month". New in version 3.7.
cssclass_year
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year". New in version 3.7.
cssclass_year_head
The CSS class for the table head for the whole year (used by formatyear()). The default value is "year". New in version 3.7.
Note that although the naming for the above described class attributes is singular (e.g. cssclass_month cssclass_noday), one can replace the single CSS class with a space separated list of CSS classes, for example: "text-bold text-red"
Here is an example how HTMLCalendar can be customized: class CustomHTMLCal(calendar.HTMLCalendar):
cssclasses = [style + " text-nowrap" for style in
calendar.HTMLCalendar.cssclasses]
cssclass_month_head = "text-center month-head"
cssclass_month = "text-center month"
cssclass_year = "text-italic lead" | python.library.calendar#calendar.HTMLCalendar |
cssclasses
A list of CSS classes used for each weekday. The default class list is: cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
more styles can be added for each day: cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]
Note that the length of this list must be seven items. | python.library.calendar#calendar.HTMLCalendar.cssclasses |
cssclasses_weekday_head
A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses. New in version 3.7. | python.library.calendar#calendar.HTMLCalendar.cssclasses_weekday_head |
cssclass_month
The CSS class for the whole month’s table (used by formatmonth()). The default value is "month". New in version 3.7. | python.library.calendar#calendar.HTMLCalendar.cssclass_month |
cssclass_month_head
The month’s head CSS class (used by formatmonthname()). The default value is "month". New in version 3.7. | python.library.calendar#calendar.HTMLCalendar.cssclass_month_head |
cssclass_noday
The CSS class for a weekday occurring in the previous or coming month. New in version 3.7. | python.library.calendar#calendar.HTMLCalendar.cssclass_noday |
cssclass_year
The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year". New in version 3.7. | python.library.calendar#calendar.HTMLCalendar.cssclass_year |
cssclass_year_head
The CSS class for the table head for the whole year (used by formatyear()). The default value is "year". New in version 3.7. | python.library.calendar#calendar.HTMLCalendar.cssclass_year_head |
formatmonth(theyear, themonth, withyear=True)
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used. | python.library.calendar#calendar.HTMLCalendar.formatmonth |
formatyear(theyear, width=3)
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row. | python.library.calendar#calendar.HTMLCalendar.formatyear |
formatyearpage(theyear, width=3, css='calendar.css', encoding=None)
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding). | python.library.calendar#calendar.HTMLCalendar.formatyearpage |
calendar.isleap(year)
Returns True if year is a leap year, otherwise False. | python.library.calendar#calendar.isleap |
calendar.leapdays(y1, y2)
Returns the number of leap years in the range from y1 to y2 (exclusive), where y1 and y2 are years. This function works for ranges spanning a century change. | python.library.calendar#calendar.leapdays |
class calendar.LocaleHTMLCalendar(firstweekday=0, locale=None)
This subclass of HTMLCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. | python.library.calendar#calendar.LocaleHTMLCalendar |
class calendar.LocaleTextCalendar(firstweekday=0, locale=None)
This subclass of TextCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode. | python.library.calendar#calendar.LocaleTextCalendar |
calendar.month(theyear, themonth, w=0, l=0)
Returns a month’s calendar in a multi-line string using the formatmonth() of the TextCalendar class. | python.library.calendar#calendar.month |
calendar.monthcalendar(year, month)
Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month are represented by zeros. Each week begins with Monday unless set by setfirstweekday(). | python.library.calendar#calendar.monthcalendar |
calendar.monthrange(year, month)
Returns weekday of first day of the month and number of days in month, for the specified year and month. | python.library.calendar#calendar.monthrange |
calendar.month_abbr
An array that represents the abbreviated months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_abbr[0] is the empty string. | python.library.calendar#calendar.month_abbr |
calendar.month_name
An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_name[0] is the empty string. | python.library.calendar#calendar.month_name |
calendar.prcal(year, w=0, l=0, c=6, m=3)
Prints the calendar for an entire year as returned by calendar(). | python.library.calendar#calendar.prcal |
calendar.prmonth(theyear, themonth, w=0, l=0)
Prints a month’s calendar as returned by month(). | python.library.calendar#calendar.prmonth |
calendar.setfirstweekday(weekday)
Sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience. For example, to set the first weekday to Sunday: import calendar
calendar.setfirstweekday(calendar.SUNDAY) | python.library.calendar#calendar.setfirstweekday |
class calendar.TextCalendar(firstweekday=0)
This class can be used to generate plain text calendars. TextCalendar instances have the following methods:
formatmonth(theyear, themonth, w=0, l=0)
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.
prmonth(theyear, themonth, w=0, l=0)
Print a month’s calendar as returned by formatmonth().
formatyear(theyear, w=2, l=1, c=6, m=3)
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.
pryear(theyear, w=2, l=1, c=6, m=3)
Print the calendar for an entire year as returned by formatyear(). | python.library.calendar#calendar.TextCalendar |
formatmonth(theyear, themonth, w=0, l=0)
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. | python.library.calendar#calendar.TextCalendar.formatmonth |
formatyear(theyear, w=2, l=1, c=6, m=3)
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent. | python.library.calendar#calendar.TextCalendar.formatyear |
prmonth(theyear, themonth, w=0, l=0)
Print a month’s calendar as returned by formatmonth(). | python.library.calendar#calendar.TextCalendar.prmonth |
pryear(theyear, w=2, l=1, c=6, m=3)
Print the calendar for an entire year as returned by formatyear(). | python.library.calendar#calendar.TextCalendar.pryear |
calendar.timegm(tuple)
An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse. | python.library.calendar#calendar.timegm |
calendar.weekday(year, month, day)
Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31). | python.library.calendar#calendar.weekday |
calendar.weekheader(n)
Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday. | python.library.calendar#calendar.weekheader |
callable(object)
Return True if the object argument appears callable, False if not. If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method. New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2. | python.library.functions#callable |
cgi — Common Gateway Interface support Source code: Lib/cgi.py Support module for Common Gateway Interface (CGI) scripts. This module defines a number of utilities for use by CGI scripts written in Python. Introduction A CGI script is invoked by an HTTP server, usually to process user input submitted through an HTML <FORM> or <ISINDEX> element. Most often, CGI scripts live in the server’s special cgi-bin directory. The HTTP server places all sorts of information about the request (such as the client’s hostname, the requested URL, the query string, and lots of other goodies) in the script’s shell environment, executes the script, and sends the script’s output back to the client. The script’s input is connected to the client too, and sometimes the form data is read this way; at other times the form data is passed via the “query string” part of the URL. This module is intended to take care of the different cases and provide a simpler interface to the Python script. It also provides a number of utilities that help in debugging scripts, and the latest addition is support for file uploads from a form (if your browser supports it). The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is following. Python code to generate a minimal header section looks like this: print("Content-Type: text/html") # HTML is following
print() # blank line, end of headers
The second section is usually HTML, which allows the client software to display nicely formatted text with header, in-line images, etc. Here’s Python code that prints a simple piece of HTML: print("<TITLE>CGI script output</TITLE>")
print("<H1>This is my first CGI script</H1>")
print("Hello, world!")
Using the cgi module Begin by writing import cgi. When you write a new script, consider adding these lines: import cgitb
cgitb.enable()
This activates a special exception handler that will display detailed reports in the Web browser if any errors occur. If you’d rather not show the guts of your program to users of your script, you can have the reports saved to files instead, with code like this: import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")
It’s very helpful to use this feature during script development. The reports produced by cgitb provide information that can save you a lot of time in tracking down bugs. You can always remove the cgitb line later when you have tested your script and are confident that it works correctly. To get at submitted form data, use the FieldStorage class. If the form contains non-ASCII characters, use the encoding keyword parameter set to the value of the encoding defined for the document. It is usually contained in the META tag in the HEAD section of the HTML document or by the Content-Type header). This reads the form contents from the standard input or the environment (depending on the value of various environment variables set according to the CGI standard). Since it may consume standard input, it should be instantiated only once. The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator, and also supports the standard dictionary method keys() and the built-in function len(). Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep_blank_values keyword parameter when creating the FieldStorage instance. For instance, the following code (which assumes that the Content-Type header and blank line have already been printed) checks that the fields name and addr are both set to a non-empty string: form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
print("<H1>Error</H1>")
print("Please fill in the name and addr fields.")
return
print("<p>name:", form["name"].value)
print("<p>addr:", form["addr"].value)
...further form processing here...
Here the fields, accessed through form[key], are themselves instances of FieldStorage (or MiniFieldStorage, depending on the form encoding). The value attribute of the instance yields the string value of the field. The getvalue() method returns this string value directly; it also accepts an optional second argument as a default to return if the requested key is not present. If the submitted form data contains more than one field with the same name, the object retrieved by form[key] is not a FieldStorage or MiniFieldStorage instance but a list of such instances. Similarly, in this situation, form.getvalue(key) would return a list of strings. If you expect this possibility (when your HTML form contains multiple fields with the same name), use the getlist() method, which always returns a list of values (so that you do not need to special-case the single item case). For example, this code concatenates any number of username fields, separated by commas: value = form.getlist("username")
usernames = ",".join(value)
If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as bytes. This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute. You can then read the data from the file attribute before it is automatically closed as part of the garbage collection of the FieldStorage instance (the read() and readline() methods will return bytes): fileitem = form["userfile"]
if fileitem.file:
# It's an uploaded file; count lines
linecount = 0
while True:
line = fileitem.file.readline()
if not line: break
linecount = linecount + 1
FieldStorage objects also support being used in a with statement, which will automatically close them when done. If an error is encountered when obtaining the contents of an uploaded file (for example, when the user interrupts the form submission by clicking on a Back or Cancel button) the done attribute of the object for the field will be set to the value -1. The file upload draft standard entertains the possibility of uploading multiple files from one field (using a recursive multipart/* encoding). When this occurs, the item will be a dictionary-like FieldStorage item. This can be determined by testing its type attribute, which should be multipart/form-data (or perhaps another MIME type matching multipart/*). In this case, it can be iterated over recursively just like the top-level form object. When a form is submitted in the “old” format (as the query string or as a single data part of type application/x-www-form-urlencoded), the items will actually be instances of the class MiniFieldStorage. In this case, the list, file, and filename attributes are always None. A form submitted via POST that also has a query string will contain both FieldStorage and MiniFieldStorage items. Changed in version 3.4: The file attribute is automatically closed upon the garbage collection of the creating FieldStorage instance. Changed in version 3.5: Added support for the context management protocol to the FieldStorage class. Higher Level Interface The previous section explains how to read CGI form data using the FieldStorage class. This section describes a higher level interface which was added to this class to allow one to do it in a more readable and intuitive way. The interface doesn’t make the techniques described in previous sections obsolete — they are still useful to process file uploads efficiently, for example. The interface consists of two simple methods. Using the methods you can process form data in a generic way, without the need to worry whether only one or more values were posted under one name. In the previous section, you learned to write following code anytime you expected a user to post more than one value under one name: item = form.getvalue("item")
if isinstance(item, list):
# The user is requesting more than one item.
else:
# The user is requesting only one item.
This situation is common for example when a form contains a group of multiple checkboxes with the same name: <input type="checkbox" name="item" value="1" />
<input type="checkbox" name="item" value="2" />
In most situations, however, there’s only one form control with a particular name in a form and then you expect and need only one value associated with this name. So you write a script containing for example this code: user = form.getvalue("user").upper()
The problem with the code is that you should never expect that a client will provide valid input to your scripts. For example, if a curious user appends another user=foo pair to the query string, then the script would crash, because in this situation the getvalue("user") method call returns a list instead of a string. Calling the upper() method on a list is not valid (since lists do not have a method of this name) and results in an AttributeError exception. Therefore, the appropriate way to read form data values was to always use the code which checks whether the obtained value is a single value or a list of values. That’s annoying and leads to less readable scripts. A more convenient approach is to use the methods getfirst() and getlist() provided by this higher level interface.
FieldStorage.getfirst(name, default=None)
This method always returns only one value associated with form field name. The method returns only the first value in case that more values were posted under such name. Please note that the order in which the values are received may vary from browser to browser and should not be counted on. 1 If no such form field or value exists then the method returns the value specified by the optional parameter default. This parameter defaults to None if not specified.
FieldStorage.getlist(name)
This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists.
Using these methods you can write nice compact code: import cgi
form = cgi.FieldStorage()
user = form.getfirst("user", "").upper() # This way it's safe.
for item in form.getlist("item"):
do_something(item)
Functions These are useful if you want more control, or if you want to employ some of the algorithms implemented in this module in other circumstances.
cgi.parse(fp=None, environ=os.environ, keep_blank_values=False, strict_parsing=False, separator="&")
Parse a query in the environment or from a file (the file defaults to sys.stdin). The keep_blank_values, strict_parsing and separator parameters are passed to urllib.parse.parse_qs() unchanged.
cgi.parse_multipart(fp, pdict, encoding="utf-8", errors="replace", separator="&")
Parse input of type multipart/form-data (for file uploads). Arguments are fp for the input file, pdict for a dictionary containing other parameters in the Content-Type header, and encoding, the request encoding. Returns a dictionary just like urllib.parse.parse_qs(): keys are the field names, each value is a list of values for that field. For non-file fields, the value is a list of strings. This is easy to use but not much good if you are expecting megabytes to be uploaded — in that case, use the FieldStorage class instead which is much more flexible. Changed in version 3.7: Added the encoding and errors parameters. For non-file fields, the value is now a list of strings, not bytes. Changed in version 3.9.2: Added the separator parameter.
cgi.parse_header(string)
Parse a MIME header (such as Content-Type) into a main value and a dictionary of parameters.
cgi.test()
Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.
cgi.print_environ()
Format the shell environment in HTML.
cgi.print_form(form)
Format a form in HTML.
cgi.print_directory()
Format the current directory in HTML.
cgi.print_environ_usage()
Print a list of useful (used by CGI) environment variables in HTML.
Caring about security There’s one important rule: if you invoke an external program (via the os.system() or os.popen() functions. or others with similar functionality), make very sure you don’t pass arbitrary strings received from the client to the shell. This is a well-known security hole whereby clever hackers anywhere on the Web can exploit a gullible CGI script to invoke arbitrary shell commands. Even parts of the URL or field names cannot be trusted, since the request doesn’t have to come from your form! To be on the safe side, if you must pass a string gotten from a form to a shell command, you should make sure the string contains only alphanumeric characters, dashes, underscores, and periods. Installing your CGI script on a Unix system Read the documentation for your HTTP server and check with your local system administrator to find the directory where CGI scripts should be installed; usually this is in a directory cgi-bin in the server tree. Make sure that your script is readable and executable by “others”; the Unix file mode should be 0o755 octal (use chmod 0755 filename). Make sure that the first line of the script contains #! starting in column 1 followed by the pathname of the Python interpreter, for instance: #!/usr/local/bin/python
Make sure the Python interpreter exists and is executable by “others”. Make sure that any files your script needs to read or write are readable or writable, respectively, by “others” — their mode should be 0o644 for readable and 0o666 for writable. This is because, for security reasons, the HTTP server executes your script as user “nobody”, without any special privileges. It can only read (write, execute) files that everybody can read (write, execute). The current directory at execution time is also different (it is usually the server’s cgi-bin directory) and the set of environment variables is also different from what you get when you log in. In particular, don’t count on the shell’s search path for executables (PATH) or the Python module search path (PYTHONPATH) to be set to anything interesting. If you need to load modules from a directory which is not on Python’s default module search path, you can change the path in your script, before importing other modules. For example: import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
sys.path.insert(0, "/usr/local/lib/python")
(This way, the directory inserted last will be searched first!) Instructions for non-Unix systems will vary; check your HTTP server’s documentation (it will usually have a section on CGI scripts). Testing your CGI script Unfortunately, a CGI script will generally not run when you try it from the command line, and a script that works perfectly from the command line may fail mysteriously when run from the server. There’s one reason why you should still test your script from the command line: if it contains a syntax error, the Python interpreter won’t execute it at all, and the HTTP server will most likely send a cryptic error to the client. Assuming your script has no syntax errors, yet it does not work, you have no choice but to read the next section. Debugging CGI scripts First of all, check for trivial installation errors — reading the section above on installing your CGI script carefully can save you a lot of time. If you wonder whether you have understood the installation procedure correctly, try installing a copy of this module file (cgi.py) as a CGI script. When invoked as a script, the file will dump its environment and the contents of the form in HTML form. Give it the right mode etc, and send it a request. If it’s installed in the standard cgi-bin directory, it should be possible to send it a request by entering a URL into your browser of the form: http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
If this gives an error of type 404, the server cannot find the script – perhaps you need to install it in a different directory. If it gives another error, there’s an installation problem that you should fix before trying to go any further. If you get a nicely formatted listing of the environment and form content (in this example, the fields should be listed as “addr” with value “At Home” and “name” with value “Joe Blow”), the cgi.py script has been installed correctly. If you follow the same procedure for your own script, you should now be able to debug it. The next step could be to call the cgi module’s test() function from your script: replace its main code with the single statement cgi.test()
This should produce the same results as those gotten from installing the cgi.py file itself. When an ordinary Python script raises an unhandled exception (for whatever reason: of a typo in a module name, a file that can’t be opened, etc.), the Python interpreter prints a nice traceback and exits. While the Python interpreter will still do this when your CGI script raises an exception, most likely the traceback will end up in one of the HTTP server’s log files, or be discarded altogether. Fortunately, once you have managed to get your script to execute some code, you can easily send tracebacks to the Web browser using the cgitb module. If you haven’t done so already, just add the lines: import cgitb
cgitb.enable()
to the top of your script. Then try running it again; when a problem occurs, you should see a detailed report that will likely make apparent the cause of the crash. If you suspect that there may be a problem in importing the cgitb module, you can use an even more robust approach (which only uses built-in modules): import sys
sys.stderr = sys.stdout
print("Content-Type: text/plain")
print()
...your code here...
This relies on the Python interpreter to print the traceback. The content type of the output is set to plain text, which disables all HTML processing. If your script works, the raw HTML will be displayed by your client. If it raises an exception, most likely after the first two lines have been printed, a traceback will be displayed. Because no HTML interpretation is going on, the traceback will be readable. Common problems and solutions Most HTTP servers buffer the output from CGI scripts until the script is completed. This means that it is not possible to display a progress report on the client’s display while the script is running. Check the installation instructions above. Check the HTTP server’s log files. (tail -f logfile in a separate window may be useful!) Always check a script for syntax errors first, by doing something like python script.py. If your script does not have any syntax errors, try adding import cgitb;
cgitb.enable() to the top of the script. When invoking external programs, make sure they can be found. Usually, this means using absolute path names — PATH is usually not set to a very useful value in a CGI script. When reading or writing external files, make sure they can be read or written by the userid under which your CGI script will be running: this is typically the userid under which the web server is running, or some explicitly specified userid for a web server’s suexec feature. Don’t try to give a CGI script a set-uid mode. This doesn’t work on most systems, and is a security liability as well. Footnotes
1
Note that some recent versions of the HTML specification do state what order the field values should be supplied in, but knowing whether a request was received from a conforming browser, or even from a browser at all, is tedious and error-prone. | python.library.cgi |
FieldStorage.getfirst(name, default=None)
This method always returns only one value associated with form field name. The method returns only the first value in case that more values were posted under such name. Please note that the order in which the values are received may vary from browser to browser and should not be counted on. 1 If no such form field or value exists then the method returns the value specified by the optional parameter default. This parameter defaults to None if not specified. | python.library.cgi#cgi.FieldStorage.getfirst |
FieldStorage.getlist(name)
This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists. | python.library.cgi#cgi.FieldStorage.getlist |
cgi.parse(fp=None, environ=os.environ, keep_blank_values=False, strict_parsing=False, separator="&")
Parse a query in the environment or from a file (the file defaults to sys.stdin). The keep_blank_values, strict_parsing and separator parameters are passed to urllib.parse.parse_qs() unchanged. | python.library.cgi#cgi.parse |
cgi.parse_header(string)
Parse a MIME header (such as Content-Type) into a main value and a dictionary of parameters. | python.library.cgi#cgi.parse_header |
cgi.parse_multipart(fp, pdict, encoding="utf-8", errors="replace", separator="&")
Parse input of type multipart/form-data (for file uploads). Arguments are fp for the input file, pdict for a dictionary containing other parameters in the Content-Type header, and encoding, the request encoding. Returns a dictionary just like urllib.parse.parse_qs(): keys are the field names, each value is a list of values for that field. For non-file fields, the value is a list of strings. This is easy to use but not much good if you are expecting megabytes to be uploaded — in that case, use the FieldStorage class instead which is much more flexible. Changed in version 3.7: Added the encoding and errors parameters. For non-file fields, the value is now a list of strings, not bytes. Changed in version 3.9.2: Added the separator parameter. | python.library.cgi#cgi.parse_multipart |
cgi.print_directory()
Format the current directory in HTML. | python.library.cgi#cgi.print_directory |
cgi.print_environ()
Format the shell environment in HTML. | python.library.cgi#cgi.print_environ |
cgi.print_environ_usage()
Print a list of useful (used by CGI) environment variables in HTML. | python.library.cgi#cgi.print_environ_usage |
cgi.print_form(form)
Format a form in HTML. | python.library.cgi#cgi.print_form |
cgi.test()
Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form. | python.library.cgi#cgi.test |
cgitb — Traceback manager for CGI scripts Source code: Lib/cgitb.py The cgitb module provides a special exception handler for Python scripts. (Its name is a bit misleading. It was originally designed to display extensive traceback information in HTML for CGI scripts. It was later generalized to also display this information in plain text.) After this module is activated, if an uncaught exception occurs, a detailed, formatted report will be displayed. The report includes a traceback showing excerpts of the source code for each level, as well as the values of the arguments and local variables to currently running functions, to help you debug the problem. Optionally, you can save this information to a file instead of sending it to the browser. To enable this feature, simply add this to the top of your CGI script: import cgitb
cgitb.enable()
The options to the enable() function control whether the report is displayed in the browser and whether the report is logged to a file for later analysis.
cgitb.enable(display=1, logdir=None, context=5, format="html")
This function causes the cgitb module to take over the interpreter’s default handling for exceptions by setting the value of sys.excepthook. The optional argument display defaults to 1 and can be set to 0 to suppress sending the traceback to the browser. If the argument logdir is present, the traceback reports are written to files. The value of logdir should be a directory where these files will be placed. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5. If the optional argument format is "html", the output is formatted as HTML. Any other value forces plain text output. The default value is "html".
cgitb.text(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as text and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5.
cgitb.html(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as HTML and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5.
cgitb.handler(info=None)
This function handles an exception using the default settings (that is, show a report in the browser, but don’t log to a file). This can be used when you’ve caught an exception and want to report it using cgitb. The optional info argument should be a 3-tuple containing an exception type, exception value, and traceback object, exactly like the tuple returned by sys.exc_info(). If the info argument is not supplied, the current exception is obtained from sys.exc_info(). | python.library.cgitb |
cgitb.enable(display=1, logdir=None, context=5, format="html")
This function causes the cgitb module to take over the interpreter’s default handling for exceptions by setting the value of sys.excepthook. The optional argument display defaults to 1 and can be set to 0 to suppress sending the traceback to the browser. If the argument logdir is present, the traceback reports are written to files. The value of logdir should be a directory where these files will be placed. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5. If the optional argument format is "html", the output is formatted as HTML. Any other value forces plain text output. The default value is "html". | python.library.cgitb#cgitb.enable |
cgitb.handler(info=None)
This function handles an exception using the default settings (that is, show a report in the browser, but don’t log to a file). This can be used when you’ve caught an exception and want to report it using cgitb. The optional info argument should be a 3-tuple containing an exception type, exception value, and traceback object, exactly like the tuple returned by sys.exc_info(). If the info argument is not supplied, the current exception is obtained from sys.exc_info(). | python.library.cgitb#cgitb.handler |
cgitb.html(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as HTML and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5. | python.library.cgitb#cgitb.html |
cgitb.text(info, context=5)
This function handles the exception described by info (a 3-tuple containing the result of sys.exc_info()), formatting its traceback as text and returning the result as a string. The optional argument context is the number of lines of context to display around the current line of source code in the traceback; this defaults to 5. | python.library.cgitb#cgitb.text |
exception ChildProcessError
Raised when an operation on a child process failed. Corresponds to errno ECHILD. | python.library.exceptions#ChildProcessError |
chr(i)
Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord(). The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range. | python.library.functions#chr |
chunk — Read IFF chunked data Source code: Lib/chunk.py This module provides an interface for reading files that use EA IFF 85 chunks. 1 This format is used in at least the Audio Interchange File Format (AIFF/AIFF-C) and the Real Media File Format (RMFF). The WAVE audio file format is closely related and can also be read using this module. A chunk has the following structure:
Offset Length Contents
0 4 Chunk ID
4 4 Size of chunk in big-endian byte order, not including the header
8 n Data bytes, where n is the size given in the preceding field
8 + n 0 or 1 Pad byte needed if n is odd and chunk alignment is used The ID is a 4-byte string which identifies the type of chunk. The size field (a 32-bit value, encoded using big-endian byte order) gives the size of the chunk data, not including the 8-byte header. Usually an IFF-type file consists of one or more chunks. The proposed usage of the Chunk class defined here is to instantiate an instance at the start of each chunk and read from the instance until it reaches the end, after which a new instance can be instantiated. At the end of the file, creating a new instance will fail with an EOFError exception.
class chunk.Chunk(file, align=True, bigendian=True, inclheader=False)
Class which represents a chunk. The file argument is expected to be a file-like object. An instance of this class is specifically allowed. The only method that is needed is read(). If the methods seek() and tell() are present and don’t raise an exception, they are also used. If these methods are present and raise an exception, they are expected to not have altered the object. If the optional argument align is true, chunks are assumed to be aligned on 2-byte boundaries. If align is false, no alignment is assumed. The default value is true. If the optional argument bigendian is false, the chunk size is assumed to be in little-endian order. This is needed for WAVE audio files. The default value is true. If the optional argument inclheader is true, the size given in the chunk header includes the size of the header. The default value is false. A Chunk object supports the following methods:
getname()
Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk.
getsize()
Returns the size of the chunk.
close()
Close and skip to the end of the chunk. This does not close the underlying file.
The remaining methods will raise OSError if called after the close() method has been called. Before Python 3.3, they used to raise IOError, now an alias of OSError.
isatty()
Returns False.
seek(pos, whence=0)
Set the chunk’s current position. The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file’s end). There is no return value. If the underlying file does not allow seek, only forward seeks are allowed.
tell()
Return the current position into the chunk.
read(size=-1)
Read at most size bytes from the chunk (less if the read hits the end of the chunk before obtaining size bytes). If the size argument is negative or omitted, read all data until the end of the chunk. An empty bytes object is returned when the end of the chunk is encountered immediately.
skip()
Skip to the end of the chunk. All further calls to read() for the chunk will return b''. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk.
Footnotes
1
“EA IFF 85” Standard for Interchange Format Files, Jerry Morrison, Electronic Arts, January 1985. | python.library.chunk |
class chunk.Chunk(file, align=True, bigendian=True, inclheader=False)
Class which represents a chunk. The file argument is expected to be a file-like object. An instance of this class is specifically allowed. The only method that is needed is read(). If the methods seek() and tell() are present and don’t raise an exception, they are also used. If these methods are present and raise an exception, they are expected to not have altered the object. If the optional argument align is true, chunks are assumed to be aligned on 2-byte boundaries. If align is false, no alignment is assumed. The default value is true. If the optional argument bigendian is false, the chunk size is assumed to be in little-endian order. This is needed for WAVE audio files. The default value is true. If the optional argument inclheader is true, the size given in the chunk header includes the size of the header. The default value is false. A Chunk object supports the following methods:
getname()
Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk.
getsize()
Returns the size of the chunk.
close()
Close and skip to the end of the chunk. This does not close the underlying file.
The remaining methods will raise OSError if called after the close() method has been called. Before Python 3.3, they used to raise IOError, now an alias of OSError.
isatty()
Returns False.
seek(pos, whence=0)
Set the chunk’s current position. The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file’s end). There is no return value. If the underlying file does not allow seek, only forward seeks are allowed.
tell()
Return the current position into the chunk.
read(size=-1)
Read at most size bytes from the chunk (less if the read hits the end of the chunk before obtaining size bytes). If the size argument is negative or omitted, read all data until the end of the chunk. An empty bytes object is returned when the end of the chunk is encountered immediately.
skip()
Skip to the end of the chunk. All further calls to read() for the chunk will return b''. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. | python.library.chunk#chunk.Chunk |
close()
Close and skip to the end of the chunk. This does not close the underlying file. | python.library.chunk#chunk.Chunk.close |
getname()
Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk. | python.library.chunk#chunk.Chunk.getname |
getsize()
Returns the size of the chunk. | python.library.chunk#chunk.Chunk.getsize |
isatty()
Returns False. | python.library.chunk#chunk.Chunk.isatty |
read(size=-1)
Read at most size bytes from the chunk (less if the read hits the end of the chunk before obtaining size bytes). If the size argument is negative or omitted, read all data until the end of the chunk. An empty bytes object is returned when the end of the chunk is encountered immediately. | python.library.chunk#chunk.Chunk.read |
seek(pos, whence=0)
Set the chunk’s current position. The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file’s end). There is no return value. If the underlying file does not allow seek, only forward seeks are allowed. | python.library.chunk#chunk.Chunk.seek |
skip()
Skip to the end of the chunk. All further calls to read() for the chunk will return b''. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. | python.library.chunk#chunk.Chunk.skip |
tell()
Return the current position into the chunk. | python.library.chunk#chunk.Chunk.tell |
class.mro()
This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__. | python.library.stdtypes#class.mro |
class.__bases__
The tuple of base classes of a class object. | python.library.stdtypes#class.__bases__ |
class.__mro__
This attribute is a tuple of classes that are considered when looking for base classes during method resolution. | python.library.stdtypes#class.__mro__ |
class.__subclasses__()
Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. The list is in definition order. Example: >>> int.__subclasses__()
[<class 'bool'>] | python.library.stdtypes#class.__subclasses__ |
@classmethod
Transform a method into a class method. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function decorator – see Function definitions for details. A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section. For more information on class methods, see The standard type hierarchy. Changed in version 3.9: Class methods can now wrap other descriptors such as property(). | python.library.functions#classmethod |
cmath — Mathematical functions for complex numbers This module provides access to mathematical functions for complex numbers. The functions in this module accept integers, floating-point numbers or complex numbers as arguments. They will also accept any Python object that has either a __complex__() or a __float__() method: these methods are used to convert the object to a complex or floating-point number, respectively, and the function is then applied to the result of the conversion. Note On platforms with hardware and system-level support for signed zeros, functions involving branch cuts are continuous on both sides of the branch cut: the sign of the zero distinguishes one side of the branch cut from the other. On platforms that do not support signed zeros the continuity is as specified below. Conversions to and from polar coordinates A Python complex number z is stored internally using rectangular or Cartesian coordinates. It is completely determined by its real part z.real and its imaginary part z.imag. In other words: z == z.real + z.imag*1j
Polar coordinates give an alternative way to represent a complex number. In polar coordinates, a complex number z is defined by the modulus r and the phase angle phi. The modulus r is the distance from z to the origin, while the phase phi is the counterclockwise angle, measured in radians, from the positive x-axis to the line segment that joins the origin to z. The following functions can be used to convert from the native rectangular coordinates to polar coordinates and back.
cmath.phase(x)
Return the phase of x (also known as the argument of x), as a float. phase(x) is equivalent to math.atan2(x.imag,
x.real). The result lies in the range [-π, π], and the branch cut for this operation lies along the negative real axis, continuous from above. On systems with support for signed zeros (which includes most systems in current use), this means that the sign of the result is the same as the sign of x.imag, even when x.imag is zero: >>> phase(complex(-1.0, 0.0))
3.141592653589793
>>> phase(complex(-1.0, -0.0))
-3.141592653589793
Note The modulus (absolute value) of a complex number x can be computed using the built-in abs() function. There is no separate cmath module function for this operation.
cmath.polar(x)
Return the representation of x in polar coordinates. Returns a pair (r, phi) where r is the modulus of x and phi is the phase of x. polar(x) is equivalent to (abs(x),
phase(x)).
cmath.rect(r, phi)
Return the complex number x with polar coordinates r and phi. Equivalent to r * (math.cos(phi) + math.sin(phi)*1j).
Power and logarithmic functions
cmath.exp(x)
Return e raised to the power x, where e is the base of natural logarithms.
cmath.log(x[, base])
Returns the logarithm of x to the given base. If the base is not specified, returns the natural logarithm of x. There is one branch cut, from 0 along the negative real axis to -∞, continuous from above.
cmath.log10(x)
Return the base-10 logarithm of x. This has the same branch cut as log().
cmath.sqrt(x)
Return the square root of x. This has the same branch cut as log().
Trigonometric functions
cmath.acos(x)
Return the arc cosine of x. There are two branch cuts: One extends right from 1 along the real axis to ∞, continuous from below. The other extends left from -1 along the real axis to -∞, continuous from above.
cmath.asin(x)
Return the arc sine of x. This has the same branch cuts as acos().
cmath.atan(x)
Return the arc tangent of x. There are two branch cuts: One extends from 1j along the imaginary axis to ∞j, continuous from the right. The other extends from -1j along the imaginary axis to -∞j, continuous from the left.
cmath.cos(x)
Return the cosine of x.
cmath.sin(x)
Return the sine of x.
cmath.tan(x)
Return the tangent of x.
Hyperbolic functions
cmath.acosh(x)
Return the inverse hyperbolic cosine of x. There is one branch cut, extending left from 1 along the real axis to -∞, continuous from above.
cmath.asinh(x)
Return the inverse hyperbolic sine of x. There are two branch cuts: One extends from 1j along the imaginary axis to ∞j, continuous from the right. The other extends from -1j along the imaginary axis to -∞j, continuous from the left.
cmath.atanh(x)
Return the inverse hyperbolic tangent of x. There are two branch cuts: One extends from 1 along the real axis to ∞, continuous from below. The other extends from -1 along the real axis to -∞, continuous from above.
cmath.cosh(x)
Return the hyperbolic cosine of x.
cmath.sinh(x)
Return the hyperbolic sine of x.
cmath.tanh(x)
Return the hyperbolic tangent of x.
Classification functions
cmath.isfinite(x)
Return True if both the real and imaginary parts of x are finite, and False otherwise. New in version 3.2.
cmath.isinf(x)
Return True if either the real or the imaginary part of x is an infinity, and False otherwise.
cmath.isnan(x)
Return True if either the real or the imaginary part of x is a NaN, and False otherwise.
cmath.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Return True if the values a and b are close to each other and False otherwise. Whether or not two values are considered close is determined according to given absolute and relative tolerances. rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero. abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero. If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol). The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN. inf and -inf are only considered close to themselves. New in version 3.5. See also PEP 485 – A function for testing approximate equality
Constants
cmath.pi
The mathematical constant π, as a float.
cmath.e
The mathematical constant e, as a float.
cmath.tau
The mathematical constant τ, as a float. New in version 3.6.
cmath.inf
Floating-point positive infinity. Equivalent to float('inf'). New in version 3.6.
cmath.infj
Complex number with zero real part and positive infinity imaginary part. Equivalent to complex(0.0, float('inf')). New in version 3.6.
cmath.nan
A floating-point “not a number” (NaN) value. Equivalent to float('nan'). New in version 3.6.
cmath.nanj
Complex number with zero real part and NaN imaginary part. Equivalent to complex(0.0, float('nan')). New in version 3.6.
Note that the selection of functions is similar, but not identical, to that in module math. The reason for having two modules is that some users aren’t interested in complex numbers, and perhaps don’t even know what they are. They would rather have math.sqrt(-1) raise an exception than return a complex number. Also note that the functions defined in cmath always return a complex number, even if the answer can be expressed as a real number (in which case the complex number has an imaginary part of zero). A note on branch cuts: They are curves along which the given function fails to be continuous. They are a necessary feature of many complex functions. It is assumed that if you need to compute with complex functions, you will understand about branch cuts. Consult almost any (not too elementary) book on complex variables for enlightenment. For information of the proper choice of branch cuts for numerical purposes, a good reference should be the following: See also Kahan, W: Branch cuts for complex elementary functions; or, Much ado about nothing’s sign bit. In Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165–211. | python.library.cmath |
cmath.acos(x)
Return the arc cosine of x. There are two branch cuts: One extends right from 1 along the real axis to ∞, continuous from below. The other extends left from -1 along the real axis to -∞, continuous from above. | python.library.cmath#cmath.acos |
cmath.acosh(x)
Return the inverse hyperbolic cosine of x. There is one branch cut, extending left from 1 along the real axis to -∞, continuous from above. | python.library.cmath#cmath.acosh |
cmath.asin(x)
Return the arc sine of x. This has the same branch cuts as acos(). | python.library.cmath#cmath.asin |
cmath.asinh(x)
Return the inverse hyperbolic sine of x. There are two branch cuts: One extends from 1j along the imaginary axis to ∞j, continuous from the right. The other extends from -1j along the imaginary axis to -∞j, continuous from the left. | python.library.cmath#cmath.asinh |
cmath.atan(x)
Return the arc tangent of x. There are two branch cuts: One extends from 1j along the imaginary axis to ∞j, continuous from the right. The other extends from -1j along the imaginary axis to -∞j, continuous from the left. | python.library.cmath#cmath.atan |
cmath.atanh(x)
Return the inverse hyperbolic tangent of x. There are two branch cuts: One extends from 1 along the real axis to ∞, continuous from below. The other extends from -1 along the real axis to -∞, continuous from above. | python.library.cmath#cmath.atanh |
cmath.cos(x)
Return the cosine of x. | python.library.cmath#cmath.cos |
cmath.cosh(x)
Return the hyperbolic cosine of x. | python.library.cmath#cmath.cosh |
cmath.e
The mathematical constant e, as a float. | python.library.cmath#cmath.e |
cmath.exp(x)
Return e raised to the power x, where e is the base of natural logarithms. | python.library.cmath#cmath.exp |
cmath.inf
Floating-point positive infinity. Equivalent to float('inf'). New in version 3.6. | python.library.cmath#cmath.inf |
cmath.infj
Complex number with zero real part and positive infinity imaginary part. Equivalent to complex(0.0, float('inf')). New in version 3.6. | python.library.cmath#cmath.infj |
cmath.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Return True if the values a and b are close to each other and False otherwise. Whether or not two values are considered close is determined according to given absolute and relative tolerances. rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero. abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero. If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol). The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN. inf and -inf are only considered close to themselves. New in version 3.5. See also PEP 485 – A function for testing approximate equality | python.library.cmath#cmath.isclose |
cmath.isfinite(x)
Return True if both the real and imaginary parts of x are finite, and False otherwise. New in version 3.2. | python.library.cmath#cmath.isfinite |
cmath.isinf(x)
Return True if either the real or the imaginary part of x is an infinity, and False otherwise. | python.library.cmath#cmath.isinf |
cmath.isnan(x)
Return True if either the real or the imaginary part of x is a NaN, and False otherwise. | python.library.cmath#cmath.isnan |
cmath.log(x[, base])
Returns the logarithm of x to the given base. If the base is not specified, returns the natural logarithm of x. There is one branch cut, from 0 along the negative real axis to -∞, continuous from above. | python.library.cmath#cmath.log |
cmath.log10(x)
Return the base-10 logarithm of x. This has the same branch cut as log(). | python.library.cmath#cmath.log10 |
cmath.nan
A floating-point “not a number” (NaN) value. Equivalent to float('nan'). New in version 3.6. | python.library.cmath#cmath.nan |
cmath.nanj
Complex number with zero real part and NaN imaginary part. Equivalent to complex(0.0, float('nan')). New in version 3.6. | python.library.cmath#cmath.nanj |
cmath.phase(x)
Return the phase of x (also known as the argument of x), as a float. phase(x) is equivalent to math.atan2(x.imag,
x.real). The result lies in the range [-π, π], and the branch cut for this operation lies along the negative real axis, continuous from above. On systems with support for signed zeros (which includes most systems in current use), this means that the sign of the result is the same as the sign of x.imag, even when x.imag is zero: >>> phase(complex(-1.0, 0.0))
3.141592653589793
>>> phase(complex(-1.0, -0.0))
-3.141592653589793 | python.library.cmath#cmath.phase |
cmath.pi
The mathematical constant π, as a float. | python.library.cmath#cmath.pi |
cmath.polar(x)
Return the representation of x in polar coordinates. Returns a pair (r, phi) where r is the modulus of x and phi is the phase of x. polar(x) is equivalent to (abs(x),
phase(x)). | python.library.cmath#cmath.polar |
cmath.rect(r, phi)
Return the complex number x with polar coordinates r and phi. Equivalent to r * (math.cos(phi) + math.sin(phi)*1j). | python.library.cmath#cmath.rect |
cmath.sin(x)
Return the sine of x. | python.library.cmath#cmath.sin |
cmath.sinh(x)
Return the hyperbolic sine of x. | python.library.cmath#cmath.sinh |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.