├── .assets ├── cover_en.jpg └── cover_zh.jpg ├── .gitattributes ├── README.md ├── The Python Standard Library by Example.pdf ├── abc ├── abc_abc_base.py ├── abc_abstractproperty.py ├── abc_abstractproperty_rw.py ├── abc_base.py ├── abc_class_static.py ├── abc_concrete_method.py ├── abc_find_subclasses.py ├── abc_incomplete.py ├── abc_register.py └── abc_subclass.py ├── argparse ├── argparse_FileType.py ├── argparse_action.py ├── argparse_arguments.py ├── argparse_choices.py ├── argparse_conflict_handler_resolve.py ├── argparse_conflict_handler_resolve2.py ├── argparse_custom_action.py ├── argparse_custom_help.py ├── argparse_default_grouping.py ├── argparse_fromfile_prefix_chars.py ├── argparse_fromfile_prefix_chars.txt ├── argparse_long.py ├── argparse_metavar_type_help_formatter.py ├── argparse_mutually_exclusive.py ├── argparse_nargs.py ├── argparse_parent_base.py ├── argparse_parent_with_group.py ├── argparse_prefix_chars.py ├── argparse_raw_description_help_formatter.py ├── argparse_raw_text_help_formatter.py ├── argparse_short.py ├── argparse_subparsers.py ├── argparse_type.py ├── argparse_uses_parent.py ├── argparse_uses_parent_with_group.py ├── argparse_with_help.py ├── argparse_with_shlex.ini ├── argparse_with_shlex.py ├── argparse_without_help.py └── tmp_file.txt ├── array ├── array_byteswap.py ├── array_file.py ├── array_sequence.py ├── array_string.py └── array_tobytes.py ├── asyncio ├── asyncio_as_completed.py ├── asyncio_call_at.py ├── asyncio_call_later.py ├── asyncio_call_soon.py ├── asyncio_cancel_task.py ├── asyncio_cancel_task2.py ├── asyncio_condition.py ├── asyncio_coroutine.py ├── asyncio_coroutine_chain.py ├── asyncio_coroutine_return.py ├── asyncio_create_task.py ├── asyncio_debug.py ├── asyncio_echo_client_coroutine.py ├── asyncio_echo_client_protocol.py ├── asyncio_echo_client_ssl.py ├── asyncio_echo_server_coroutine.py ├── asyncio_echo_server_generator.py ├── asyncio_echo_server_protocol.py ├── asyncio_echo_server_ssl.py ├── asyncio_ensure_future.py ├── asyncio_event.py ├── asyncio_executor_process.py ├── asyncio_executor_thread.py ├── asyncio_future_await.py ├── asyncio_future_callback.py ├── asyncio_future_event_loop.py ├── asyncio_gather.py ├── asyncio_generator.py ├── asyncio_getaddrinfo.py ├── asyncio_getnameinfo.py ├── asyncio_lock.py ├── asyncio_queue.py ├── asyncio_signal.py ├── asyncio_stop.py ├── asyncio_subprocess_coroutine.py ├── asyncio_subprocess_coroutine_write.py ├── asyncio_subprocess_protocol.py ├── asyncio_wait.py └── asyncio_wait_timeout.py ├── atexit ├── atexit_decorator.py ├── atexit_exception.py ├── atexit_keyboardinterrupt.py ├── atexit_multiple.py ├── atexit_os_exit.py ├── atexit_signal_child.py ├── atexit_signal_parent.py ├── atexit_simple.py ├── atexit_sys_exit.py ├── atexit_unregister.py └── atexit_unregister_not_registered.py ├── base64 ├── base64_b64decode.py ├── base64_b64encode.py ├── base64_base16.py ├── base64_base32.py ├── base64_base85.py └── base64_urlsafe.py ├── bisect ├── bisect_example.py └── bisect_example2.py ├── bz2 ├── bz2_file_compresslevel.py ├── bz2_file_read.py ├── bz2_file_seek.py ├── bz2_file_write.py ├── bz2_file_writelines.py ├── bz2_incremental.py ├── bz2_lengths.py ├── bz2_memory.py ├── bz2_mixed.py ├── bz2_server.py ├── bz2_unicode.py └── lorem.txt ├── calendar ├── calendar_formatyear.py ├── calendar_htmlcalendar.py ├── calendar_locale.py ├── calendar_monthcalendar.py ├── calendar_secondthursday.py ├── calendar_textcalendar.py └── calendar_yeardays2calendar.py ├── cgitb ├── LOGS │ └── tmpdl2oafqt.txt ├── cgitb_basic_traceback.py ├── cgitb_exception_properties.py ├── cgitb_extended_traceback.py ├── cgitb_html_output.py ├── cgitb_local_vars.py ├── cgitb_log_exception.py ├── cgitb_more_context.py └── cgitb_with_classes.py ├── cmd ├── cmd_arg_completion.py ├── cmd_arguments.py ├── cmd_argv.py ├── cmd_attributes.py ├── cmd_do_help.py ├── cmd_do_shell.py ├── cmd_file.py ├── cmd_file.txt ├── cmd_illustrate_methods.py └── cmd_simple.py ├── codecs ├── codecs_bom.py ├── codecs_bom_create_file.py ├── codecs_bom_detection.py ├── codecs_decode.py ├── codecs_decode_error.py ├── codecs_encode_error.py ├── codecs_encodedfile.py ├── codecs_encodings.py ├── codecs_incremental_bz2.py ├── codecs_invertcaps.py ├── codecs_invertcaps_charmap.py ├── codecs_invertcaps_error.py ├── codecs_invertcaps_register.py ├── codecs_open_read.py ├── codecs_open_write.py ├── codecs_register.py ├── codecs_rot13.py ├── codecs_socket.py ├── codecs_socket_fail.py ├── codecs_to_hex.py ├── codecs_zlib.py ├── decode_error.txt ├── encode_error.txt ├── nonnative-encoded.txt ├── utf-16.txt ├── utf-32.txt └── utf-8.txt ├── collections ├── collections_chainmap_new_child.py ├── collections_chainmap_new_child_explicit.py ├── collections_chainmap_read.py ├── collections_chainmap_reorder.py ├── collections_chainmap_update_behind.py ├── collections_chainmap_update_directly.py ├── collections_counter_arithmetic.py ├── collections_counter_elements.py ├── collections_counter_get_values.py ├── collections_counter_init.py ├── collections_counter_most_common.py ├── collections_counter_update.py ├── collections_defaultdict.py ├── collections_deque.py ├── collections_deque_both_ends.py ├── collections_deque_consuming.py ├── collections_deque_maxlen.py ├── collections_deque_populating.py ├── collections_deque_rotate.py ├── collections_namedtuple_asdict.py ├── collections_namedtuple_bad_fields.py ├── collections_namedtuple_fields.py ├── collections_namedtuple_immutable.py ├── collections_namedtuple_person.py ├── collections_namedtuple_rename.py ├── collections_namedtuple_replace.py ├── collections_ordereddict_equality.py ├── collections_ordereddict_iter.py ├── collections_ordereddict_move_to_end.py └── collections_tuple.py ├── compileall ├── compileall_compile_dir.py ├── compileall_compile_file.py ├── compileall_exclude_dirs.py ├── compileall_path.py ├── compileall_recursion_depth.py └── examples │ ├── a.py │ └── subdir │ └── b.py ├── concurrent.futures ├── futures_as_completed.py ├── futures_context_manager.py ├── futures_future_callback.py ├── futures_future_callback_cancel.py ├── futures_future_exception.py ├── futures_process_pool_broken.py ├── futures_process_pool_map.py ├── futures_thread_pool_map.py └── futures_thread_pool_submit.py ├── configparser ├── allow_no_value.ini ├── configparser_allow_no_value.py ├── configparser_custom_types.py ├── configparser_defaults.py ├── configparser_escape.py ├── configparser_example.py ├── configparser_extendedinterpolation.py ├── configparser_has_option.py ├── configparser_has_section.py ├── configparser_interpolation.py ├── configparser_interpolation_defaults.py ├── configparser_interpolation_error.py ├── configparser_interpolation_recursion.py ├── configparser_multiline.py ├── configparser_nointerpolation.py ├── configparser_populate.py ├── configparser_read.py ├── configparser_read_many.py ├── configparser_remove.py ├── configparser_structure.py ├── configparser_structure_dict.py ├── configparser_unicode.py ├── configparser_value_types.py ├── configparser_write.py ├── custom_types.ini ├── escape.ini ├── extended_interpolation.ini ├── interpolation.ini ├── interpolation_defaults.ini ├── multiline.ini ├── multisection.ini ├── simple.ini ├── types.ini ├── unicode.ini └── with-defaults.ini ├── contextlib ├── contextlib_api.py ├── contextlib_api_error.py ├── contextlib_api_other_object.py ├── contextlib_closing.py ├── contextlib_context_managers.py ├── contextlib_contextmanager.py ├── contextlib_contextmanager_decorator.py ├── contextlib_decorator.py ├── contextlib_exitstack_callbacks.py ├── contextlib_exitstack_callbacks_decorator.py ├── contextlib_exitstack_callbacks_error.py ├── contextlib_exitstack_enter_context.py ├── contextlib_exitstack_enter_context_errors.py ├── contextlib_exitstack_pop_all.py ├── contextlib_file.py ├── contextlib_ignore_error.py ├── contextlib_redirect.py └── contextlib_suppress.py ├── copy ├── copy_deep.py ├── copy_hooks.py ├── copy_recursion.py └── copy_shallow.py ├── csv ├── csv_dialect.py ├── csv_dialect_sniffer.py ├── csv_dialect_variations.py ├── csv_dictreader.py ├── csv_dictwriter.py ├── csv_list_dialects.py ├── csv_reader.py ├── csv_writer.py ├── csv_writer_quoted.py ├── testdata.csv ├── testdata.pipes ├── testlinebreak.csv ├── testout.csv └── testout_quoted.csv ├── datetime ├── datetime_comparing.py ├── datetime_date.py ├── datetime_date_fromordinal.py ├── datetime_date_fromothervalue.py ├── datetime_date_isocalendar.py ├── datetime_date_math.py ├── datetime_date_minmax.py ├── datetime_date_replace.py ├── datetime_datetime.py ├── datetime_datetime_combine.py ├── datetime_datetime_math.py ├── datetime_datetime_minmax.py ├── datetime_datetime_strptime.py ├── datetime_format.py ├── datetime_time.py ├── datetime_time_minmax.py ├── datetime_time_resolution.py ├── datetime_timedelta.py ├── datetime_timedelta_math.py ├── datetime_timedelta_total_seconds.py └── datetime_timezone.py ├── dbm ├── dbm_existing.py ├── dbm_intkeys.py ├── dbm_intvalue.py ├── dbm_new.py └── dbm_whichdb.py ├── decimal ├── decimal_context_manager.py ├── decimal_create.py ├── decimal_format.py ├── decimal_getcontext.py ├── decimal_instance_context.py ├── decimal_log.py ├── decimal_operators.py ├── decimal_precision.py ├── decimal_rounding.py ├── decimal_special.py ├── decimal_thread_context.py └── decimal_tuple.py ├── difflib ├── difflib_context.py ├── difflib_data.py ├── difflib_differ.py ├── difflib_html.py ├── difflib_junk.py ├── difflib_ndiff.py ├── difflib_seq.py ├── difflib_unified.py └── output.diff ├── dis ├── dis_class.py ├── dis_constant_folding.py ├── dis_eliminate_loop.py ├── dis_faster_loop.py ├── dis_fastest_loop.py ├── dis_function.py ├── dis_loops.py ├── dis_show_code.py ├── dis_simple.py ├── dis_slow_loop.py ├── dis_string.py ├── dis_test_loop.py └── dis_traceback.py ├── doctest ├── doctest_blankline.py ├── doctest_blankline_fail.py ├── doctest_docstrings.py ├── doctest_ellipsis.py ├── doctest_extra_space.py ├── doctest_hashed_values.py ├── doctest_hashed_values_tests.py ├── doctest_in_help.py ├── doctest_in_help.txt ├── doctest_mutable_globals.py ├── doctest_ndiff.py ├── doctest_normalize_whitespace.py ├── doctest_private_tests.py ├── doctest_private_tests_external.py ├── doctest_simple.py ├── doctest_simple_with_docs.py ├── doctest_test_globals.py ├── doctest_testfile.py ├── doctest_testmod.py ├── doctest_testmod_other_module.py ├── doctest_tracebacks.py ├── doctest_tracebacks_no_body.py ├── doctest_unittest.py └── doctest_unpredictable.py ├── enum ├── enum_aliases.py ├── enum_comparison.py ├── enum_complex_values.py ├── enum_create.py ├── enum_intenum.py ├── enum_iterate.py ├── enum_programmatic_create.py ├── enum_programmatic_mapping.py ├── enum_tuple_values.py └── enum_unique_enforce.py ├── filecmp ├── filecmp_cmp.py ├── filecmp_cmpfiles.py ├── filecmp_dircmp_common.py ├── filecmp_dircmp_diff.py ├── filecmp_dircmp_list.py ├── filecmp_dircmp_list_filter.py ├── filecmp_dircmp_membership.py ├── filecmp_dircmp_report.py ├── filecmp_dircmp_report_full_closure.py ├── filecmp_dircmp_subdirs.py └── filecmp_mkexamples.py ├── fileinput ├── etc_hosts.txt ├── fileinput_change_subnet.py ├── fileinput_change_subnet_noisy.py ├── fileinput_example.py └── fileinput_grep.py ├── fnmatch ├── fnmatch_filter.py ├── fnmatch_fnmatch.py ├── fnmatch_fnmatchcase.py └── fnmatch_translate.py ├── fractions ├── fractions_arithmetic.py ├── fractions_create_integers.py ├── fractions_create_strings.py ├── fractions_create_strings_floats.py ├── fractions_from_decimal.py ├── fractions_from_float.py └── fractions_limit_denominator.py ├── functools ├── functools_callable.py ├── functools_cmp_to_key.py ├── functools_lru_cache.py ├── functools_lru_cache_arguments.py ├── functools_lru_cache_expire.py ├── functools_partial.py ├── functools_partialmethod.py ├── functools_reduce.py ├── functools_reduce_initializer.py ├── functools_reduce_short_sequences.py ├── functools_singledispatch.py ├── functools_singledispatch_mro.py ├── functools_total_ordering.py ├── functools_update_wrapper.py └── functools_wraps.py ├── gc ├── gc_collect.py ├── gc_debug_leak.py ├── gc_debug_saveall.py ├── gc_debug_stats.py ├── gc_get_objects.py ├── gc_get_referents.py ├── gc_get_referents_cycles.py ├── gc_get_referrers.py ├── gc_get_threshold.py └── gc_threshold.py ├── getopt ├── getopt_example.py ├── getopt_gnu.py ├── getopt_long.py └── getopt_short.py ├── getpass ├── getpass_defaults.py ├── getpass_noterminal.py ├── getpass_prompt.py └── getpass_stream.py ├── gettext ├── gettext_app_builtin.py ├── gettext_example.py ├── gettext_example_corrected.py ├── gettext_find.py ├── gettext_module_global.py └── gettext_plural.py ├── glob ├── dir │ ├── file.txt │ ├── file1.txt │ ├── file2.txt │ ├── file[.txt │ ├── file_.txt │ ├── filea.txt │ ├── fileb.txt │ └── subdir │ │ └── subfile.txt ├── glob_asterisk.py ├── glob_charrange.py ├── glob_escape.py ├── glob_extension.py ├── glob_maketestdata.py ├── glob_question.py └── glob_subdir.py ├── grp ├── grp_getgrall.py ├── grp_getgrgid_fileowner.py ├── grp_getgrgid_process.py ├── grp_getgrnam.py └── grp_groups_for_user.py ├── gzip ├── gzip_BytesIO.py ├── gzip_compresslevel.py ├── gzip_read.py ├── gzip_seek.py ├── gzip_write.py ├── gzip_writelines.py └── lorem.txt ├── hashlib ├── hashlib_algorithms.py ├── hashlib_data.py ├── hashlib_md5.py ├── hashlib_new.py ├── hashlib_sha1.py └── hashlib_update.py ├── heapq ├── heapq_extremes.py ├── heapq_heapdata.py ├── heapq_heapify.py ├── heapq_heappop.py ├── heapq_heappush.py ├── heapq_heapreplace.py ├── heapq_merge.py └── heapq_showtree.py ├── hmac ├── hmac_base64.py ├── hmac_pickle.py ├── hmac_sha.py ├── hmac_simple.py └── lorem.txt ├── http.cookies ├── http_cookies_Morsel.py ├── http_cookies_coded_value.py ├── http_cookies_js_output.py ├── http_cookies_parse.py └── http_cookies_setheaders.py ├── http.server ├── http_server_GET.py ├── http_server_POST.py ├── http_server_errors.py ├── http_server_send_header.py └── http_server_threads.py ├── imaplib ├── imaplib_append.py ├── imaplib_archive_read.py ├── imaplib_connect.py ├── imaplib_connect_fail.py ├── imaplib_delete_messages.py ├── imaplib_fetch_body.py ├── imaplib_fetch_raw.py ├── imaplib_fetch_rfc822.py ├── imaplib_fetch_separately.py ├── imaplib_list.py ├── imaplib_list_parse.py ├── imaplib_list_pattern.py ├── imaplib_list_subfolders.py ├── imaplib_search_all.py ├── imaplib_search_from.py ├── imaplib_search_subject.py ├── imaplib_select.py ├── imaplib_select_invalid.py └── imaplib_status.py ├── importlib ├── example │ ├── __init__.py │ └── submodule.py ├── importlib_find_loader.py ├── importlib_import_module.py ├── importlib_import_module_error.py ├── importlib_reload.py ├── importlib_submodule.py └── importlib_suffixes.py ├── inspect ├── example.py ├── inspect_currentframe.py ├── inspect_formatargspec.py ├── inspect_getclasstree.py ├── inspect_getclasstree_unique.py ├── inspect_getcomments_method.py ├── inspect_getcomments_module.py ├── inspect_getdoc.py ├── inspect_getmembers_class.py ├── inspect_getmembers_class_methods.py ├── inspect_getmembers_class_methods_b.py ├── inspect_getmembers_instance.py ├── inspect_getmembers_module.py ├── inspect_getmembers_module_class.py ├── inspect_getmro.py ├── inspect_getsource_class.py ├── inspect_getsource_method.py ├── inspect_getsourcelines_method.py ├── inspect_signature_bind.py ├── inspect_signature_bind_partial.py ├── inspect_signature_function.py └── inspect_stack.py ├── io ├── io_bytesio.py ├── io_stringio.py └── io_textiowrapper.py ├── ipaddress ├── ipaddress_addresses.py ├── ipaddress_interfaces.py ├── ipaddress_network_iterate.py ├── ipaddress_network_iterate_hosts.py ├── ipaddress_network_membership.py └── ipaddress_networks.py ├── itertools ├── itertools_accumulate.py ├── itertools_accumulate_custom.py ├── itertools_chain.py ├── itertools_chain_from_iterable.py ├── itertools_combinations.py ├── itertools_combinations_with_replacement.py ├── itertools_compress.py ├── itertools_count.py ├── itertools_count_step.py ├── itertools_cycle.py ├── itertools_dropwhile.py ├── itertools_filter.py ├── itertools_filterfalse.py ├── itertools_groupby.py ├── itertools_groupby_seq.py ├── itertools_islice.py ├── itertools_map.py ├── itertools_permutations.py ├── itertools_product.py ├── itertools_product_ordering.py ├── itertools_product_repeat.py ├── itertools_repeat.py ├── itertools_repeat_map.py ├── itertools_repeat_zip.py ├── itertools_starmap.py ├── itertools_takewhile.py ├── itertools_tee.py ├── itertools_tee_error.py ├── itertools_zip.py └── itertools_zip_longest.py ├── json ├── json_compact_encoding.py ├── json_decoder_object_hook.py ├── json_dump_default.py ├── json_dump_file.py ├── json_encoder_default.py ├── json_encoder_iterable.py ├── json_indent.py ├── json_load_file.py ├── json_load_object_hook.py ├── json_mixed_data.py ├── json_myobj.py ├── json_simple_types.py ├── json_simple_types_decode.py ├── json_skipkeys.py └── json_sort_keys.py ├── linecache ├── linecache_data.py ├── linecache_empty_line.py ├── linecache_example.py ├── linecache_getline.py ├── linecache_missing_file.py ├── linecache_out_of_range.py └── linecache_path_search.py ├── locale ├── locale_atof.py ├── locale_currency.py ├── locale_date.py ├── locale_delocalize.py ├── locale_env.py ├── locale_grouping.py └── locale_list.py ├── logging ├── logging_capture_warnings.py ├── logging_file_example.py ├── logging_level_example.py ├── logging_modules_example.py └── logging_rotatingfile_example.py ├── mailbox ├── mailbox_maildir_add_flag.py ├── mailbox_maildir_create.py ├── mailbox_maildir_folders.py ├── mailbox_maildir_read.py ├── mailbox_maildir_remove.py ├── mailbox_maildir_set_flags.py ├── mailbox_maildir_set_subdir.py ├── mailbox_mbox_create.py ├── mailbox_mbox_read.py └── mailbox_mbox_remove.py ├── math ├── math_constants.py ├── math_copysign.py ├── math_degrees.py ├── math_distance_2_points.py ├── math_erf.py ├── math_erfc.py ├── math_exp.py ├── math_expm1.py ├── math_fabs.py ├── math_factorial.py ├── math_fmod.py ├── math_frexp.py ├── math_fsum.py ├── math_gamma.py ├── math_gcd.py ├── math_hyperbolic.py ├── math_hypot.py ├── math_integers.py ├── math_inverse_trig.py ├── math_isclose.py ├── math_isclose_abs_tol.py ├── math_isclose_inf.py ├── math_isfinite.py ├── math_isinf.py ├── math_isnan.py ├── math_ldexp.py ├── math_lgamma.py ├── math_log.py ├── math_log10.py ├── math_log1p.py ├── math_log2.py ├── math_modf.py ├── math_overflow.py ├── math_pow.py ├── math_radians.py ├── math_sqrt.py └── math_trig.py ├── mmap ├── lorem.txt ├── lorem_copy.txt ├── mmap_read.py ├── mmap_regex.py ├── mmap_write_copy.py └── mmap_write_slice.py ├── multiprocessing ├── multiprocessing_condition.py ├── multiprocessing_daemon.py ├── multiprocessing_daemon_join.py ├── multiprocessing_daemon_join_timeout.py ├── multiprocessing_event.py ├── multiprocessing_exitcode.py ├── multiprocessing_get_logger.py ├── multiprocessing_import_main.py ├── multiprocessing_import_worker.py ├── multiprocessing_lock.py ├── multiprocessing_log_to_stderr.py ├── multiprocessing_manager_dict.py ├── multiprocessing_mapreduce.py ├── multiprocessing_names.py ├── multiprocessing_namespaces.py ├── multiprocessing_namespaces_mutable.py ├── multiprocessing_pool.py ├── multiprocessing_pool_maxtasksperchild.py ├── multiprocessing_producer_consumer.py ├── multiprocessing_queue.py ├── multiprocessing_semaphore.py ├── multiprocessing_simple.py ├── multiprocessing_simpleargs.py ├── multiprocessing_subclass.py ├── multiprocessing_terminate.py └── multiprocessing_wordcount.py ├── operator ├── operator_attrgetter.py ├── operator_boolean.py ├── operator_classes.py ├── operator_comparisons.py ├── operator_inplace.py ├── operator_itemgetter.py ├── operator_math.py └── operator_sequences.py ├── os.path ├── ospath_abspath.py ├── ospath_basename.py ├── ospath_commonpath.py ├── ospath_commonprefix.py ├── ospath_dirname.py ├── ospath_expanduser.py ├── ospath_expandvars.py ├── ospath_join.py ├── ospath_normpath.py ├── ospath_properties.py ├── ospath_split.py ├── ospath_splitext.py └── ospath_tests.py ├── os ├── os_access.py ├── os_cwd_example.py ├── os_directories.py ├── os_environ_example.py ├── os_exec_example.py ├── os_fork_example.py ├── os_kill_example.py ├── os_listdir.py ├── os_process_id_example.py ├── os_process_user_example.py ├── os_rename_replace.py ├── os_scandir.py ├── os_spawn_example.py ├── os_stat.py ├── os_stat_chmod.py ├── os_stat_chmod_example.txt ├── os_strerror.py ├── os_symlinks.py ├── os_system_background.py ├── os_system_example.py ├── os_system_shell.py ├── os_wait_example.py ├── os_waitpid_example.py └── os_walk.py ├── pathlib ├── example.txt ├── pathlib_chmod.py ├── pathlib_chmod_example.txt ├── pathlib_convenience.py ├── pathlib_from_existing.py ├── pathlib_glob.py ├── pathlib_iterdir.py ├── pathlib_joinpath.py ├── pathlib_mkdir.py ├── pathlib_name.py ├── pathlib_operator.py ├── pathlib_ownership.py ├── pathlib_parents.py ├── pathlib_parts.py ├── pathlib_read_write.py ├── pathlib_resolve.py ├── pathlib_rglob.py ├── pathlib_rmdir.py ├── pathlib_stat.py ├── pathlib_symlink_to.py ├── pathlib_touch.py ├── pathlib_types.py └── pathlib_unlink.py ├── pdb ├── lorem.txt ├── pdb_break.py ├── pdb_break_remote.py ├── pdb_function_arguments.py ├── pdb_interact.py ├── pdb_jump.py ├── pdb_next.py ├── pdb_no_jump.py ├── pdb_post_mortem.py ├── pdb_pp.py ├── pdb_run.py ├── pdb_script.py ├── pdb_set_trace.py └── pdb_step.py ├── pickle ├── pickle_cycle.py ├── pickle_dump_to_file_1.py ├── pickle_load_from_file_1.py ├── pickle_load_from_file_2.py ├── pickle_state.py ├── pickle_stream.py ├── pickle_string.py └── pickle_unpickle.py ├── pkgutil ├── __init__.py ├── demopkg1 │ ├── __init__.py │ └── shared.py ├── demopkg2 │ ├── __init__.py │ └── overloaded.py ├── develop │ ├── demopkg2 │ │ ├── __init__.py │ │ └── overloaded.py │ └── nested │ │ ├── __init__.py │ │ ├── second │ │ ├── __init__.py │ │ └── deep.py │ │ └── shallow.py ├── extension │ ├── __init__.py │ └── demopkg1 │ │ ├── __init__.py │ │ └── not_shared.py ├── nested │ ├── __init__.py │ ├── second │ │ ├── __init__.py │ │ └── deep.py │ └── shallow.py ├── os_one │ └── demopkg1 │ │ ├── __init__.py │ │ └── not_shared.py ├── os_two │ └── demopkg1 │ │ ├── __init__.py │ │ └── not_shared.py ├── pkgutil_devel.py ├── pkgutil_extend_path.py ├── pkgutil_get_data.py ├── pkgutil_get_data_zip.py ├── pkgutil_nested.py ├── pkgutil_os_specific.py └── pkgwithdata │ └── __init__.py ├── platform ├── platform_architecture.py ├── platform_os_info.py ├── platform_platform.py └── platform_python.py ├── pprint ├── pprint_arbitrary_object.py ├── pprint_compact.py ├── pprint_data.py ├── pprint_depth.py ├── pprint_pformat.py ├── pprint_pprint.py ├── pprint_recursion.py └── pprint_width.py ├── profile ├── profile_fibonacci_memoized.py ├── profile_fibonacci_raw.py ├── profile_runctx.py ├── profile_stats.py ├── profile_stats_callers.py └── profile_stats_restricted.py ├── pwd ├── pwd_getpwall.py ├── pwd_getpwnam.py ├── pwd_getpwuid_fileowner.py └── pwd_getpwuid_process.py ├── pyclbr ├── pyclbr_example.py ├── pyclbr_readmodule.py └── pyclbr_readmodule_ex.py ├── queue ├── fetch_podcasts.py ├── queue_fifo.py ├── queue_lifo.py └── queue_priority.py ├── random ├── random_choice.py ├── random_randint.py ├── random_random.py ├── random_random_class.py ├── random_randrange.py ├── random_sample.py ├── random_seed.py ├── random_shuffle.py ├── random_state.py ├── random_system_random.py └── random_uniform.py ├── re ├── re_anchoring.py ├── re_charset.py ├── re_charset_dot.py ├── re_charset_exclude.py ├── re_charset_ranges.py ├── re_email_compact.py ├── re_email_verbose.py ├── re_email_with_name.py ├── re_escape_codes.py ├── re_escape_escapes.py ├── re_findall.py ├── re_finditer.py ├── re_flags_ascii.py ├── re_flags_dotall.py ├── re_flags_embedded.py ├── re_flags_ignorecase.py ├── re_flags_multiline.py ├── re_fullmatch.py ├── re_groups.py ├── re_groups_alternative.py ├── re_groups_individual.py ├── re_groups_match.py ├── re_groups_named.py ├── re_groups_nested.py ├── re_groups_noncapturing.py ├── re_id.py ├── re_look_ahead.py ├── re_look_behind.py ├── re_match.py ├── re_negative_look_ahead.py ├── re_negative_look_behind.py ├── re_paragraphs_findall.py ├── re_refer_to_group.py ├── re_refer_to_named_group.py ├── re_repetition.py ├── re_repetition_non_greedy.py ├── re_search_substring.py ├── re_simple.py ├── re_simple_compiled.py ├── re_simple_match.py ├── re_split.py ├── re_split_groups.py ├── re_sub.py ├── re_sub_count.py ├── re_sub_named_groups.py ├── re_subn.py ├── re_test_patterns.py └── re_test_patterns_groups.py ├── readline ├── readline_buffer.py ├── readline_completer.py ├── readline_history.py ├── readline_hooks.py ├── readline_parse_and_bind.py └── readline_read_init_file.py ├── resource ├── resource_getrlimit.py ├── resource_getrusage.py ├── resource_setrlimit_cpu.py └── resource_setrlimit_nofile.py ├── sched ├── sched_basic.py ├── sched_cancel.py ├── sched_overlap.py └── sched_priority.py ├── select ├── select_echo_multiclient.py ├── select_echo_server.py ├── select_echo_server_timeout.py ├── select_echo_slow_client.py └── select_poll_echo_server.py ├── selectors ├── selectors_echo_client.py └── selectors_echo_server.py ├── shelve ├── shelve_create.py ├── shelve_existing.py ├── shelve_readonly.py ├── shelve_withoutwriteback.py └── shelve_writeback.py ├── shlex ├── apostrophe.txt ├── comments.txt ├── quotes.txt ├── shlex_errors.py ├── shlex_example.py ├── shlex_posix.py ├── shlex_quote.py ├── shlex_source.py ├── shlex_split.py ├── shlex_table.py └── shlex_whitespace.py ├── shutil ├── config.ini ├── file_to_change.txt ├── shutil_copy.py ├── shutil_copy2.py ├── shutil_copyfile.py ├── shutil_copyfileobj.py ├── shutil_copymode.py ├── shutil_copystat.py ├── shutil_copytree.py ├── shutil_copytree_verbose.py ├── shutil_disk_usage.py ├── shutil_get_archive_formats.py ├── shutil_get_unpack_formats.py ├── shutil_make_archive.py ├── shutil_move.py ├── shutil_rmtree.py ├── shutil_unpack_archive.py ├── shutil_which.py └── shutil_which_regular_file.py ├── signal ├── signal_alarm.py ├── signal_getsignal.py ├── signal_ignore.py ├── signal_signal.py ├── signal_threads.py └── signal_threads_alarm.py ├── site ├── multiple_pth │ ├── a.pth │ ├── b.pth │ ├── from_a │ │ └── mymodule.py │ └── from_b │ │ └── mymodule.py ├── site_addsitedir.py ├── site_enable_user_site.py ├── site_import_path.py ├── site_user_base.py ├── with_modules │ └── mymodule.py ├── with_pth │ ├── pymotw.pth │ └── subdir │ │ └── mymodule.py ├── with_sitecustomize │ ├── site_sitecustomize.py │ └── sitecustomize.py └── with_usercustomize │ ├── site_usercustomize.py │ └── usercustomize.py ├── smtpd ├── smtpd_custom.py ├── smtpd_debug.py ├── smtpd_proxy.py └── smtpd_senddata.py ├── smtplib ├── smtplib_authenticated.py ├── smtplib_sendmail.py └── smtplib_verify.py ├── socket ├── socket_address_packing.py ├── socket_binary_client.py ├── socket_binary_server.py ├── socket_echo_client.py ├── socket_echo_client_dgram.py ├── socket_echo_client_easy.py ├── socket_echo_client_explicit.py ├── socket_echo_client_uds.py ├── socket_echo_server.py ├── socket_echo_server_any.py ├── socket_echo_server_dgram.py ├── socket_echo_server_explicit.py ├── socket_echo_server_uds.py ├── socket_getaddrinfo.py ├── socket_getaddrinfo_extra_args.py ├── socket_getfqdn.py ├── socket_gethostbyaddr.py ├── socket_gethostbyname.py ├── socket_gethostbyname_ex.py ├── socket_gethostname.py ├── socket_getprotobyname.py ├── socket_getservbyname.py ├── socket_getservbyport.py ├── socket_ipv6_address_packing.py ├── socket_multicast_receiver.py ├── socket_multicast_sender.py └── socket_socketpair.py ├── socketserver ├── socketserver_echo.py ├── socketserver_echo_simple.py ├── socketserver_forking.py └── socketserver_threaded.py ├── sqlite3 ├── sqlite3_argument_named.py ├── sqlite3_argument_positional.py ├── sqlite3_argument_update.py ├── sqlite3_autocommit.py ├── sqlite3_create_aggregate.py ├── sqlite3_create_function.py ├── sqlite3_create_schema.py ├── sqlite3_createdb.py ├── sqlite3_cursor_description.py ├── sqlite3_custom_type.py ├── sqlite3_custom_type_column.py ├── sqlite3_date_types.py ├── sqlite3_isolation_levels.py ├── sqlite3_iterdump.py ├── sqlite3_load_csv.py ├── sqlite3_load_extension_fts3.py ├── sqlite3_memory.py ├── sqlite3_regex.py ├── sqlite3_row_factory.py ├── sqlite3_select_tasks.py ├── sqlite3_select_variations.py ├── sqlite3_set_authorizer.py ├── sqlite3_threading.py ├── sqlite3_transaction_commit.py └── sqlite3_transaction_rollback.py ├── statistics ├── statistics_mean.py ├── statistics_median.py ├── statistics_median_grouped.py ├── statistics_mode.py └── statistics_variance.py ├── string ├── string_capwords.py ├── string_constants.py ├── string_template.py ├── string_template_advanced.py ├── string_template_defaultpattern.py ├── string_template_missing.py └── string_template_newsyntax.py ├── struct ├── struct_buffers.py ├── struct_endianness.py ├── struct_pack.py └── struct_unpack.py ├── subprocess ├── interaction.py ├── repeater.py ├── signal_child.py ├── signal_parent.py ├── subprocess_check_output_error_trap_output.py ├── subprocess_os_system.py ├── subprocess_pipes.py ├── subprocess_popen2.py ├── subprocess_popen3.py ├── subprocess_popen4.py ├── subprocess_popen_read.py ├── subprocess_popen_write.py ├── subprocess_run_check.py ├── subprocess_run_output.py ├── subprocess_run_output_error.py ├── subprocess_run_output_error_suppress.py ├── subprocess_run_output_error_trap.py ├── subprocess_shell_variables.py ├── subprocess_signal_parent_shell.py └── subprocess_signal_setpgrp.py ├── sys ├── package_dir_a │ ├── __init__.py │ └── example.py ├── package_dir_b │ ├── __init__.py │ └── example.py ├── sys_argv.py ├── sys_builtins.py ├── sys_byteorder.py ├── sys_current_frames.py ├── sys_displayhook.py ├── sys_exc_info.py ├── sys_excepthook.py ├── sys_exit.py ├── sys_flags.py ├── sys_float_info.py ├── sys_getrefcount.py ├── sys_getsizeof.py ├── sys_getsizeof_custom.py ├── sys_getsizeof_object.py ├── sys_implementation.py ├── sys_int_info.py ├── sys_locations.py ├── sys_maximums.py ├── sys_meta_path.py ├── sys_modules.py ├── sys_path_hooks_noisy.py ├── sys_path_importer_cache.py ├── sys_path_modify.py ├── sys_path_show.py ├── sys_platform.py ├── sys_ps1.py ├── sys_recursionlimit.py ├── sys_settrace_call.py ├── sys_settrace_exception.py ├── sys_settrace_line.py ├── sys_settrace_return.py ├── sys_shelve_importer.py ├── sys_shelve_importer_create.py ├── sys_shelve_importer_get_data.py ├── sys_shelve_importer_missing.py ├── sys_shelve_importer_module.py ├── sys_shelve_importer_package.py ├── sys_shelve_importer_reload.py ├── sys_stdio.py ├── sys_switchinterval.py ├── sys_unicode.py └── sys_version_values.py ├── sysconfig ├── sysconfig_get_config_var.py ├── sysconfig_get_config_vars.py ├── sysconfig_get_config_vars_by_name.py ├── sysconfig_get_path.py ├── sysconfig_get_path_names.py ├── sysconfig_get_paths.py ├── sysconfig_get_platform.py ├── sysconfig_get_python_version.py └── sysconfig_get_scheme_names.py ├── tabnanny └── tabnanny_check.py ├── tarfile ├── README.txt ├── outdir │ └── README.txt ├── tarfile_add.py ├── tarfile_addfile.py ├── tarfile_addfile_string.py ├── tarfile_append.py ├── tarfile_compression.py ├── tarfile_extract.py ├── tarfile_extractall.py ├── tarfile_extractall_members.py ├── tarfile_extractfile.py ├── tarfile_getmember.py ├── tarfile_getmembers.py ├── tarfile_getnames.py └── tarfile_is_tarfile.py ├── tempfile ├── tempfile_NamedTemporaryFile.py ├── tempfile_NamedTemporaryFile_args.py ├── tempfile_SpooledTemporaryFile.py ├── tempfile_SpooledTemporaryFile_explicit.py ├── tempfile_TemporaryDirectory.py ├── tempfile_TemporaryFile.py ├── tempfile_TemporaryFile_binary.py ├── tempfile_TemporaryFile_text.py ├── tempfile_settings.py └── tempfile_tempdir.py ├── textwrap ├── textwrap_dedent.py ├── textwrap_example.py ├── textwrap_fill.py ├── textwrap_fill_width.py ├── textwrap_hanging_indent.py ├── textwrap_indent.py ├── textwrap_indent_predicate.py └── textwrap_shorten.py ├── threading ├── threading_barrier.py ├── threading_barrier_abort.py ├── threading_condition.py ├── threading_daemon.py ├── threading_daemon_join.py ├── threading_daemon_join_timeout.py ├── threading_enumerate.py ├── threading_event.py ├── threading_local.py ├── threading_local_defaults.py ├── threading_lock.py ├── threading_lock_noblock.py ├── threading_lock_reacquire.py ├── threading_lock_with.py ├── threading_names.py ├── threading_names_log.py ├── threading_rlock.py ├── threading_semaphore.py ├── threading_simple.py ├── threading_simpleargs.py ├── threading_subclass.py ├── threading_subclass_args.py └── threading_timer.py ├── time ├── time_clock_sleep.py ├── time_ctime.py ├── time_get_clock_info.py ├── time_monotonic.py ├── time_perf_counter.py ├── time_process_time.py ├── time_strptime.py ├── time_struct.py ├── time_time.py └── time_timezone.py ├── timeit ├── timeit_dictionary.py ├── timeit_example.py └── timeit_setitem.py ├── trace ├── trace_CoverageResults.py ├── trace_example │ ├── __init__.py │ ├── main.py │ └── recurse.py ├── trace_report.py ├── trace_run.py └── trace_runfunc.py ├── traceback ├── traceback_example.py ├── traceback_extract_stack.py ├── traceback_extract_tb.py ├── traceback_format_exc.py ├── traceback_format_exception.py ├── traceback_format_stack.py ├── traceback_framesummary.py ├── traceback_print_exc.py ├── traceback_print_exception.py ├── traceback_print_stack.py ├── traceback_print_tb.py ├── traceback_stacksummary.py └── traceback_tracebackexception.py ├── unittest ├── unittest_addcleanup.py ├── unittest_almostequal.py ├── unittest_equality.py ├── unittest_equality_container.py ├── unittest_exception.py ├── unittest_expectedfailure.py ├── unittest_failwithmessage.py ├── unittest_fixtures.py ├── unittest_in.py ├── unittest_outcomes.py ├── unittest_simple.py ├── unittest_skip.py ├── unittest_subtest.py └── unittest_truth.py ├── urllib.parse ├── urllib_parse_geturl.py ├── urllib_parse_parse_qs.py ├── urllib_parse_quote.py ├── urllib_parse_unquote.py ├── urllib_parse_urldefrag.py ├── urllib_parse_urlencode.py ├── urllib_parse_urlencode_doseq.py ├── urllib_parse_urljoin.py ├── urllib_parse_urljoin_with_path.py ├── urllib_parse_urlparse.py ├── urllib_parse_urlparseattrs.py ├── urllib_parse_urlsplit.py ├── urllib_parse_urlunparse.py └── urllib_parse_urlunparseextra.py ├── urllib.request ├── urllib_request_http_get_args.py ├── urllib_request_nfs_handler.py ├── urllib_request_request_header.py ├── urllib_request_request_post.py ├── urllib_request_upload_files.py ├── urllib_request_urlopen.py ├── urllib_request_urlopen_iterator.py └── urllib_request_urlopen_post.py ├── urllib.robotparser ├── robots.txt ├── urllib_robotparser_longlived.py └── urllib_robotparser_simple.py ├── uuid ├── uuid_getnode.py ├── uuid_uuid1.py ├── uuid_uuid1_othermac.py ├── uuid_uuid1_repeat.py ├── uuid_uuid3_repeat.py ├── uuid_uuid3_uuid5.py ├── uuid_uuid4.py └── uuid_uuid_objects.py ├── warnings ├── warnings_filter.py ├── warnings_filterwarnings_lineno.py ├── warnings_filterwarnings_message.py ├── warnings_filterwarnings_module.py ├── warnings_formatwarning.py ├── warnings_once.py ├── warnings_repeated.py ├── warnings_showwarning.py ├── warnings_warn.py ├── warnings_warn_raise.py └── warnings_warn_stacklevel.py ├── weakref ├── weakref_finalize.py ├── weakref_finalize_atexit.py ├── weakref_finalize_reference.py ├── weakref_finalize_reference_method.py ├── weakref_proxy.py ├── weakref_ref.py ├── weakref_ref_callback.py └── weakref_valuedict.py ├── webbrowser ├── webbrowser_get.py ├── webbrowser_open.py ├── webbrowser_open_new.py └── webbrowser_open_new_tab.py ├── xml.etree.ElementTree ├── ElementTree_XML.py ├── ElementTree_XMLID.py ├── ElementTree_create.py ├── ElementTree_create_pretty.py ├── ElementTree_csv_to_xml.py ├── ElementTree_dump_opml.py ├── ElementTree_entity_references.py ├── ElementTree_extend.py ├── ElementTree_extend_node.py ├── ElementTree_extend_node_copy.py ├── ElementTree_find_feeds_by_structure.py ├── ElementTree_find_feeds_by_tag.py ├── ElementTree_node_attributes.py ├── ElementTree_node_text.py ├── ElementTree_parse_opml.py ├── ElementTree_podcast_csv_treebuilder.py ├── ElementTree_pretty.py ├── ElementTree_show_all_events.py ├── ElementTree_show_feed_urls.py ├── ElementTree_write.py ├── ElementTree_write_method.py └── ElementTree_write_podcast_csv.py ├── xmlrpc.client ├── xmlrpc_Binary.py ├── xmlrpc_Binary_pickle.py ├── xmlrpc_MultiCall.py ├── xmlrpc_MultiCall_exception.py ├── xmlrpc_ServerProxy.py ├── xmlrpc_ServerProxy_allow_none.py ├── xmlrpc_ServerProxy_encoding.py ├── xmlrpc_ServerProxy_use_datetime.py ├── xmlrpc_ServerProxy_verbose.py ├── xmlrpc_exception.py ├── xmlrpc_server.py ├── xmlrpc_types.py ├── xmlrpc_types_nested.py └── xmlrpc_types_object.py ├── xmlrpc.server ├── xmlrpc_alternate_name.py ├── xmlrpc_alternate_name_client.py ├── xmlrpc_arbitrary_name.py ├── xmlrpc_arbitrary_name_client.py ├── xmlrpc_dotted_name.py ├── xmlrpc_dotted_name_client.py ├── xmlrpc_function.py ├── xmlrpc_function_client.py ├── xmlrpc_instance.py ├── xmlrpc_instance_client.py ├── xmlrpc_instance_dotted_names.py ├── xmlrpc_instance_dotted_names_client.py ├── xmlrpc_instance_with_prefix.py ├── xmlrpc_instance_with_prefix_client.py ├── xmlrpc_introspection.py └── xmlrpc_introspection_client.py ├── zipfile ├── README.txt ├── zipfile_append.py ├── zipfile_getinfo.py ├── zipfile_infolist.py ├── zipfile_is_zipfile.py ├── zipfile_namelist.py ├── zipfile_printdir.py ├── zipfile_pyzipfile.py ├── zipfile_read.py ├── zipfile_write.py ├── zipfile_write_arcname.py ├── zipfile_write_compression.py ├── zipfile_writestr.py └── zipfile_writestr_zipinfo.py ├── zipimport ├── __init__.py ├── example_package │ ├── README.txt │ └── __init__.py ├── zipimport_find_module.py ├── zipimport_get_code.py ├── zipimport_get_data.py ├── zipimport_get_data_nozip.py ├── zipimport_get_data_zip.py ├── zipimport_get_source.py ├── zipimport_is_package.py ├── zipimport_load_module.py └── zipimport_make_example.py └── zlib ├── lorem.txt ├── zlib_checksum_tests.py ├── zlib_checksums.py ├── zlib_compresslevel.py ├── zlib_incremental.py ├── zlib_lengths.py ├── zlib_memory.py ├── zlib_mixed.py └── zlib_server.py /.assets/cover_en.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/.assets/cover_en.jpg -------------------------------------------------------------------------------- /.assets/cover_zh.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/.assets/cover_zh.jpg -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /The Python Standard Library by Example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/The Python Standard Library by Example.pdf -------------------------------------------------------------------------------- /abc/abc_find_subclasses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import abc 11 | from abc_base import PluginBase 12 | import abc_subclass 13 | import abc_register 14 | 15 | for sc in PluginBase.__subclasses__(): 16 | print(sc.__name__) 17 | -------------------------------------------------------------------------------- /argparse/argparse_choices.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import argparse 11 | 12 | parser = argparse.ArgumentParser() 13 | 14 | parser.add_argument( 15 | '--mode', 16 | choices=('read-only', 'read-write'), 17 | ) 18 | 19 | print(parser.parse_args()) 20 | -------------------------------------------------------------------------------- /argparse/argparse_fromfile_prefix_chars.txt: -------------------------------------------------------------------------------- 1 | -a 2 | -b 3 | 2 4 | -------------------------------------------------------------------------------- /argparse/argparse_mutually_exclusive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import argparse 11 | 12 | parser = argparse.ArgumentParser() 13 | 14 | group = parser.add_mutually_exclusive_group() 15 | group.add_argument('-a', action='store_true') 16 | group.add_argument('-b', action='store_true') 17 | 18 | print(parser.parse_args()) 19 | -------------------------------------------------------------------------------- /argparse/argparse_parent_base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Parent with shared options 7 | """ 8 | 9 | #end_pymotw_header 10 | import argparse 11 | 12 | parser = argparse.ArgumentParser(add_help=False) 13 | 14 | parser.add_argument('--user', action="store") 15 | parser.add_argument('--password', action="store") 16 | -------------------------------------------------------------------------------- /argparse/argparse_with_shlex.ini: -------------------------------------------------------------------------------- 1 | [cli] 2 | options = -a -b 2 -------------------------------------------------------------------------------- /argparse/tmp_file.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/argparse/tmp_file.txt -------------------------------------------------------------------------------- /array/array_sequence.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import array 11 | import pprint 12 | 13 | a = array.array('i', range(3)) 14 | print('Initial :', a) 15 | 16 | a.extend(range(3)) 17 | print('Extended:', a) 18 | 19 | print('Slice :', a[2:5]) 20 | 21 | print('Iterator:') 22 | print(list(enumerate(a))) 23 | -------------------------------------------------------------------------------- /array/array_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import array 11 | import binascii 12 | 13 | s = b'This is the array.' 14 | a = array.array('b', s) 15 | 16 | print('As byte string:', s) 17 | print('As array :', a) 18 | print('As hex :', binascii.hexlify(a)) 19 | -------------------------------------------------------------------------------- /array/array_tobytes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import array 11 | import binascii 12 | 13 | a = array.array('i', range(5)) 14 | print('A1:', a) 15 | 16 | as_bytes = a.tobytes() 17 | print('Bytes:', binascii.hexlify(as_bytes)) 18 | 19 | a2 = array.array('i') 20 | a2.frombytes(as_bytes) 21 | print('A2:', a2) 22 | -------------------------------------------------------------------------------- /atexit/atexit_decorator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using atexit.register as a decorator. 3 | """ 4 | # end_pymotw_header 5 | import atexit 6 | 7 | 8 | @atexit.register 9 | def all_done(): 10 | print('all_done()') 11 | 12 | 13 | print('starting main program') 14 | -------------------------------------------------------------------------------- /atexit/atexit_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """If an exception is raised in an atexit callback, it is 3 | printed to the console. 4 | 5 | """ 6 | # end_pymotw_header 7 | import atexit 8 | 9 | 10 | def exit_with_exception(message): 11 | raise RuntimeError(message) 12 | 13 | 14 | atexit.register(exit_with_exception, 'Registered first') 15 | atexit.register(exit_with_exception, 'Registered second') 16 | -------------------------------------------------------------------------------- /atexit/atexit_keyboardinterrupt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """atexit functions are still called when a KeyboardInterrupt is 3 | received. 4 | 5 | """ 6 | # end_pymotw_header 7 | import atexit 8 | import sys 9 | 10 | 11 | def is_called(): 12 | print('The atexit handlers are still called') 13 | 14 | 15 | atexit.register(is_called) 16 | 17 | sys.stdout.write('Press Ctrl-C now') 18 | sys.stdout.flush() 19 | 20 | ignored = sys.stdin.readline() 21 | -------------------------------------------------------------------------------- /atexit/atexit_multiple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Register repeatedly with different arguments. 3 | """ 4 | 5 | # end_pymotw_header 6 | import atexit 7 | 8 | 9 | def my_cleanup(name): 10 | print('my_cleanup({})'.format(name)) 11 | 12 | 13 | atexit.register(my_cleanup, 'first') 14 | atexit.register(my_cleanup, 'second') 15 | atexit.register(my_cleanup, 'third') 16 | -------------------------------------------------------------------------------- /atexit/atexit_os_exit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """atexit callbacks are not invoked if we bypass normal exit and 3 | cleanup. 4 | 5 | """ 6 | 7 | # end_pymotw_header 8 | import atexit 9 | import os 10 | 11 | 12 | def not_called(): 13 | print('This should not be called') 14 | 15 | 16 | print('Registering') 17 | atexit.register(not_called) 18 | print('Registered') 19 | 20 | print('Exiting...') 21 | os._exit(0) 22 | -------------------------------------------------------------------------------- /atexit/atexit_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Simple atexit example. 3 | """ 4 | 5 | # end_pymotw_header 6 | import atexit 7 | 8 | 9 | def all_done(): 10 | print('all_done()') 11 | 12 | 13 | print('Registering') 14 | atexit.register(all_done) 15 | print('Registered') 16 | -------------------------------------------------------------------------------- /atexit/atexit_sys_exit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | """ 4 | 5 | # end_pymotw_header 6 | import atexit 7 | import sys 8 | 9 | 10 | def all_done(): 11 | print('all_done()') 12 | 13 | 14 | print('Registering') 15 | atexit.register(all_done) 16 | print('Registered') 17 | 18 | print('Exiting...') 19 | sys.exit() 20 | -------------------------------------------------------------------------------- /atexit/atexit_unregister.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Cancel registered callback 3 | """ 4 | # end_pymotw_header 5 | import atexit 6 | 7 | 8 | def my_cleanup(name): 9 | print('my_cleanup({})'.format(name)) 10 | 11 | 12 | atexit.register(my_cleanup, 'first') 13 | atexit.register(my_cleanup, 'second') 14 | atexit.register(my_cleanup, 'third') 15 | 16 | atexit.unregister(my_cleanup) 17 | -------------------------------------------------------------------------------- /atexit/atexit_unregister_not_registered.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Cancel registered callback 3 | """ 4 | # end_pymotw_header 5 | import atexit 6 | 7 | 8 | def my_cleanup(name): 9 | print('my_cleanup({})'.format(name)) 10 | 11 | 12 | if False: 13 | atexit.register(my_cleanup, 'never registered') 14 | 15 | atexit.unregister(my_cleanup) 16 | -------------------------------------------------------------------------------- /base64/base64_b64decode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import base64 11 | 12 | encoded_data = b'VGhpcyBpcyB0aGUgZGF0YSwgaW4gdGhlIGNsZWFyLg==' 13 | decoded_data = base64.b64decode(encoded_data) 14 | print('Encoded :', encoded_data) 15 | print('Decoded :', decoded_data) 16 | -------------------------------------------------------------------------------- /bz2/bz2_file_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import bz2 11 | import io 12 | 13 | with bz2.BZ2File('example.bz2', 'rb') as input: 14 | with io.TextIOWrapper(input, encoding='utf-8') as dec: 15 | print(dec.read()) 16 | -------------------------------------------------------------------------------- /bz2/lorem.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec 2 | egestas, enim et consectetuer ullamcorper, lectus ligula rutrum leo, 3 | a elementum elit tortor eu quam. Duis tincidunt nisi ut ante. Nulla 4 | facilisi. 5 | -------------------------------------------------------------------------------- /calendar/calendar_formatyear.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Print entire year calendar. 3 | """ 4 | #end_pymotw_header 5 | import calendar 6 | 7 | cal = calendar.TextCalendar(calendar.SUNDAY) 8 | print(cal.formatyear(2017, 2, 1, 1, 3)) 9 | -------------------------------------------------------------------------------- /calendar/calendar_htmlcalendar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Sample of TextCalendar output. 3 | """ 4 | #end_pymotw_header 5 | import calendar 6 | 7 | c = calendar.HTMLCalendar(calendar.SUNDAY) 8 | print(c.formatmonth(2017, 7)) 9 | -------------------------------------------------------------------------------- /calendar/calendar_locale.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Sample of TextCalendar output. 3 | """ 4 | #end_pymotw_header 5 | import calendar 6 | 7 | c = calendar.LocaleTextCalendar(locale='en_US') 8 | c.prmonth(2017, 7) 9 | 10 | print() 11 | 12 | c = calendar.LocaleTextCalendar(locale='fr_FR') 13 | c.prmonth(2017, 7) 14 | -------------------------------------------------------------------------------- /calendar/calendar_monthcalendar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Show the dates in each week of a month. 3 | """ 4 | #end_pymotw_header 5 | import calendar 6 | import pprint 7 | 8 | pprint.pprint(calendar.monthcalendar(2017, 7)) 9 | -------------------------------------------------------------------------------- /calendar/calendar_textcalendar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Sample of TextCalendar output. 3 | """ 4 | #end_pymotw_header 5 | import calendar 6 | 7 | c = calendar.TextCalendar(calendar.SUNDAY) 8 | c.prmonth(2017, 7) 9 | -------------------------------------------------------------------------------- /cgitb/cgitb_basic_traceback.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann. All rights reserved. 5 | # 6 | """Generate a traceback 7 | """ 8 | 9 | #end_pymotw_header 10 | def func2(a, divisor): 11 | return a / divisor 12 | 13 | 14 | def func1(a, b): 15 | c = b - 5 16 | return func2(a, c) 17 | 18 | func1(1, 5) 19 | -------------------------------------------------------------------------------- /cgitb/cgitb_local_vars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann. All rights reserved. 5 | # 6 | """Local variables lead to an answer 7 | """ 8 | 9 | #end_pymotw_header 10 | import cgitb 11 | cgitb.enable(format='text') 12 | 13 | 14 | def func2(a, divisor): 15 | return a / divisor 16 | 17 | 18 | def func1(a, b): 19 | c = b - 5 20 | return func2(a, c) 21 | 22 | func1(1, 5) 23 | -------------------------------------------------------------------------------- /cmd/cmd_file.txt: -------------------------------------------------------------------------------- 1 | greet 2 | greet Alice and Bob 3 | -------------------------------------------------------------------------------- /cmd/cmd_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import cmd 12 | 13 | 14 | class HelloWorld(cmd.Cmd): 15 | 16 | def do_greet(self, line): 17 | print("hello") 18 | 19 | def do_EOF(self, line): 20 | return True 21 | 22 | 23 | if __name__ == '__main__': 24 | HelloWorld().cmdloop() 25 | -------------------------------------------------------------------------------- /codecs/codecs_open_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Writing Unicode data to a file. 7 | """ 8 | 9 | #end_pymotw_header 10 | import codecs 11 | import sys 12 | 13 | encoding = sys.argv[1] 14 | filename = encoding + '.txt' 15 | 16 | print('Reading from', filename) 17 | with codecs.open(filename, mode='r', encoding=encoding) as f: 18 | print(repr(f.read())) 19 | -------------------------------------------------------------------------------- /codecs/decode_error.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/codecs/decode_error.txt -------------------------------------------------------------------------------- /codecs/encode_error.txt: -------------------------------------------------------------------------------- 1 | fran\xe7ais -------------------------------------------------------------------------------- /codecs/nonnative-encoded.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/codecs/nonnative-encoded.txt -------------------------------------------------------------------------------- /codecs/utf-16.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/codecs/utf-16.txt -------------------------------------------------------------------------------- /codecs/utf-32.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/codecs/utf-32.txt -------------------------------------------------------------------------------- /codecs/utf-8.txt: -------------------------------------------------------------------------------- 1 | français -------------------------------------------------------------------------------- /collections/collections_chainmap_update_directly.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2015 Doug Hellmann. All rights reserved. 5 | # 6 | """Updating values through a ChainMap 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | a = {'a': 'A', 'c': 'C'} 13 | b = {'b': 'B', 'c': 'D'} 14 | 15 | m = collections.ChainMap(a, b) 16 | print('Before:', m) 17 | m['c'] = 'E' 18 | print('After :', m) 19 | print('a:', a) 20 | -------------------------------------------------------------------------------- /collections/collections_counter_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Produce the elements of the counter. 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | c = collections.Counter('extremely') 13 | c['z'] = 0 14 | print(c) 15 | print(list(c.elements())) 16 | -------------------------------------------------------------------------------- /collections/collections_counter_get_values.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Updating counts. 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | c = collections.Counter('abcdaab') 13 | 14 | for letter in 'abcde': 15 | print('{} : {}'.format(letter, c[letter])) 16 | -------------------------------------------------------------------------------- /collections/collections_counter_init.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Initializing a Counter 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | print(collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])) 13 | print(collections.Counter({'a': 2, 'b': 3, 'c': 1})) 14 | print(collections.Counter(a=2, b=3, c=1)) 15 | -------------------------------------------------------------------------------- /collections/collections_counter_update.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Updating counts. 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | c = collections.Counter() 13 | print('Initial :', c) 14 | 15 | c.update('abcdaab') 16 | print('Sequence:', c) 17 | 18 | c.update({'a': 1, 'd': 5}) 19 | print('Dict :', c) 20 | -------------------------------------------------------------------------------- /collections/collections_deque.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Double-ended queue. 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | d = collections.deque('abcdefg') 13 | print('Deque:', d) 14 | print('Length:', len(d)) 15 | print('Left end:', d[0]) 16 | print('Right end:', d[-1]) 17 | 18 | d.remove('c') 19 | print('remove(c):', d) 20 | -------------------------------------------------------------------------------- /collections/collections_namedtuple_asdict.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | Person = collections.namedtuple('Person', 'name age') 13 | 14 | bob = Person(name='Bob', age=30) 15 | print('Representation:', bob) 16 | print('As Dictionary:', bob._asdict()) 17 | -------------------------------------------------------------------------------- /collections/collections_namedtuple_fields.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | Person = collections.namedtuple('Person', 'name age') 13 | 14 | bob = Person(name='Bob', age=30) 15 | print('Representation:', bob) 16 | print('Fields:', bob._fields) 17 | -------------------------------------------------------------------------------- /collections/collections_namedtuple_immutable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | Person = collections.namedtuple('Person', 'name age') 13 | 14 | pat = Person(name='Pat', age=12) 15 | print('\nRepresentation:', pat) 16 | 17 | pat.age = 21 18 | -------------------------------------------------------------------------------- /collections/collections_namedtuple_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import collections 11 | 12 | Person = collections.namedtuple('Person', 'name age') 13 | 14 | bob = Person(name='Bob', age=30) 15 | print('\nBefore:', bob) 16 | bob2 = bob._replace(name='Robert') 17 | print('After:', bob2) 18 | print('Same?:', bob is bob2) 19 | -------------------------------------------------------------------------------- /compileall/compileall_exclude_dirs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import compileall 11 | import re 12 | 13 | compileall.compile_dir( 14 | 'examples', 15 | rx=re.compile(r'/subdir'), 16 | ) 17 | -------------------------------------------------------------------------------- /compileall/compileall_path.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import compileall 11 | import sys 12 | 13 | sys.path[:] = ['examples', 'notthere'] 14 | print('sys.path =', sys.path) 15 | compileall.compile_path() 16 | -------------------------------------------------------------------------------- /compileall/compileall_recursion_depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import compileall 11 | import re 12 | 13 | compileall.compile_dir( 14 | 'examples', 15 | maxlevels=0, 16 | ) 17 | -------------------------------------------------------------------------------- /compileall/examples/a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | print('running {}'.format(__file__)) 11 | -------------------------------------------------------------------------------- /compileall/examples/subdir/b.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | print('running {}'.format(__file__)) 11 | -------------------------------------------------------------------------------- /configparser/allow_no_value.ini: -------------------------------------------------------------------------------- 1 | [flags] 2 | turn_feature_on 3 | -------------------------------------------------------------------------------- /configparser/configparser_escape.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | """Example use of ConfigParser module. 5 | """ 6 | 7 | #end_pymotw_header 8 | from configparser import ConfigParser 9 | import os 10 | 11 | filename = 'escape.ini' 12 | config = ConfigParser() 13 | config.read([filename]) 14 | 15 | value = config.get('escape', 'value') 16 | 17 | print(value) 18 | -------------------------------------------------------------------------------- /configparser/configparser_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | """Example use of ConfigParser module. 5 | """ 6 | 7 | #end_pymotw_header 8 | from configparser import ConfigParser 9 | import os 10 | 11 | filename = 'approach.ini' 12 | config = ConfigParser() 13 | config.read([filename]) 14 | 15 | url = config.get('portal', 'url') 16 | 17 | print(url) 18 | -------------------------------------------------------------------------------- /configparser/configparser_interpolation_defaults.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Reading a configuration file. 7 | """ 8 | 9 | #end_pymotw_header 10 | from configparser import ConfigParser 11 | 12 | parser = ConfigParser() 13 | parser.read('interpolation_defaults.ini') 14 | 15 | print('URL:', parser.get('bug_tracker', 'url')) 16 | -------------------------------------------------------------------------------- /configparser/configparser_multiline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2015 Doug Hellmann. 4 | """Example use of ConfigParser module. 5 | """ 6 | 7 | #end_pymotw_header 8 | from configparser import ConfigParser 9 | import os 10 | 11 | filename = 'multiline.ini' 12 | config = ConfigParser() 13 | config.read([filename]) 14 | 15 | message = config['example']['message'] 16 | 17 | print(message) 18 | -------------------------------------------------------------------------------- /configparser/configparser_nointerpolation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Disabling interpolation 7 | """ 8 | 9 | #end_pymotw_header 10 | from configparser import ConfigParser 11 | 12 | parser = ConfigParser(interpolation=None) 13 | parser.read('interpolation.ini') 14 | 15 | print('Without interpolation:', parser.get('bug_tracker', 'url')) 16 | -------------------------------------------------------------------------------- /configparser/configparser_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Reading a configuration file. 7 | """ 8 | 9 | #end_pymotw_header 10 | from configparser import ConfigParser 11 | 12 | parser = ConfigParser() 13 | parser.read('simple.ini') 14 | 15 | print(parser.get('bug_tracker', 'url')) 16 | -------------------------------------------------------------------------------- /configparser/custom_types.ini: -------------------------------------------------------------------------------- 1 | [datetimes] 2 | due_date = 2015-11-08T11:30:05.905898 -------------------------------------------------------------------------------- /configparser/escape.ini: -------------------------------------------------------------------------------- 1 | [escape] 2 | value = a literal %% must be escaped -------------------------------------------------------------------------------- /configparser/extended_interpolation.ini: -------------------------------------------------------------------------------- 1 | [intranet] 2 | server = localhost 3 | port = 8080 4 | 5 | [bug_tracker] 6 | url = http://${intranet:server}:${intranet:port}/bugs/ 7 | username = dhellmann 8 | password = SECRET 9 | -------------------------------------------------------------------------------- /configparser/interpolation.ini: -------------------------------------------------------------------------------- 1 | [bug_tracker] 2 | protocol = http 3 | server = localhost 4 | port = 8080 5 | url = %(protocol)s://%(server)s:%(port)s/bugs/ 6 | username = dhellmann 7 | password = SECRET 8 | -------------------------------------------------------------------------------- /configparser/interpolation_defaults.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | url = %(protocol)s://%(server)s:%(port)s/bugs/ 3 | protocol = http 4 | server = bugs.example.com 5 | port = 80 6 | 7 | [bug_tracker] 8 | server = localhost 9 | port = 8080 10 | username = dhellmann 11 | password = SECRET 12 | -------------------------------------------------------------------------------- /configparser/multiline.ini: -------------------------------------------------------------------------------- 1 | [example] 2 | message = This is a multi-line string. 3 | With two paragraphs. 4 | 5 | They are separated by a completely empty line. 6 | -------------------------------------------------------------------------------- /configparser/multisection.ini: -------------------------------------------------------------------------------- 1 | [bug_tracker] 2 | url = http://localhost:8080/bugs/ 3 | username = dhellmann 4 | password = SECRET 5 | 6 | [wiki] 7 | url = http://localhost:8080/wiki/ 8 | username = dhellmann 9 | password = SECRET 10 | -------------------------------------------------------------------------------- /configparser/simple.ini: -------------------------------------------------------------------------------- 1 | # This is a simple example with comments. 2 | [bug_tracker] 3 | url = http://localhost:8080/bugs/ 4 | username = dhellmann 5 | ; You should not store passwords in plain text 6 | ; configuration files. 7 | password = SECRET 8 | -------------------------------------------------------------------------------- /configparser/types.ini: -------------------------------------------------------------------------------- 1 | [ints] 2 | positive = 1 3 | negative = -5 4 | 5 | [floats] 6 | positive = 0.2 7 | negative = -3.14 8 | 9 | [booleans] 10 | number_true = 1 11 | number_false = 0 12 | yn_true = yes 13 | yn_false = no 14 | tf_true = true 15 | tf_false = false 16 | onoff_true = on 17 | onoff_false = false 18 | -------------------------------------------------------------------------------- /configparser/unicode.ini: -------------------------------------------------------------------------------- 1 | [bug_tracker] 2 | url = http://localhost:8080/bugs/ 3 | username = dhellmann 4 | password = ßéç®é† 5 | -------------------------------------------------------------------------------- /configparser/with-defaults.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | file-only = value from DEFAULT section 3 | init-and-file = value from DEFAULT section 4 | from-section = value from DEFAULT section 5 | from-vars = value from DEFAULT section 6 | 7 | [sect] 8 | section-only = value from section in file 9 | from-section = value from section in file 10 | from-vars = value from section in file 11 | -------------------------------------------------------------------------------- /contextlib/contextlib_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Files as context managers. 7 | """ 8 | 9 | #end_pymotw_header 10 | with open('/tmp/pymotw.txt', 'wt') as f: 11 | f.write('contents go here') 12 | # file is automatically closed 13 | -------------------------------------------------------------------------------- /csv/csv_dialect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | #end_pymotw_header 9 | import csv 10 | 11 | csv.register_dialect('pipes', delimiter='|') 12 | 13 | with open('testdata.pipes', 'r') as f: 14 | reader = csv.reader(f, dialect='pipes') 15 | for row in reader: 16 | print(row) 17 | -------------------------------------------------------------------------------- /csv/csv_dictreader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """Dictionary reader. 4 | """ 5 | #end_pymotw_header 6 | import csv 7 | import sys 8 | 9 | with open(sys.argv[1], 'rt') as f: 10 | reader = csv.DictReader(f) 11 | for row in reader: 12 | print(row) 13 | -------------------------------------------------------------------------------- /csv/csv_list_dialects.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """List the registered dialects. 7 | """ 8 | #end_pymotw_header 9 | import csv 10 | 11 | print(csv.list_dialects()) 12 | -------------------------------------------------------------------------------- /csv/csv_reader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Example of reading a comma separated value file. 6 | """ 7 | #end_pymotw_header 8 | import csv 9 | import sys 10 | 11 | with open(sys.argv[1], 'rt') as f: 12 | reader = csv.reader(f) 13 | for row in reader: 14 | print(row) 15 | -------------------------------------------------------------------------------- /csv/testdata.csv: -------------------------------------------------------------------------------- 1 | "Title 1","Title 2","Title 3","Title 4" 2 | 1,"a",08/18/07,"å" 3 | 2,"b",08/19/07,"∫" 4 | 3,"c",08/20/07,"ç" 5 | -------------------------------------------------------------------------------- /csv/testdata.pipes: -------------------------------------------------------------------------------- 1 | "Title 1"|"Title 2"|"Title 3" 2 | 1|"first line 3 | second line"|08/18/07 4 | -------------------------------------------------------------------------------- /csv/testlinebreak.csv: -------------------------------------------------------------------------------- 1 | "Title 1","Title 2","Title 3" 2 | 1,"first line 3 | second line",08/18/07 4 | -------------------------------------------------------------------------------- /csv/testout.csv: -------------------------------------------------------------------------------- 1 | Title 1,Title 2,Title 3,Title 4 2 | 1,a,08/01/07,å 3 | 2,b,08/02/07,∫ 4 | 3,c,08/03/07,ç 5 | -------------------------------------------------------------------------------- /csv/testout_quoted.csv: -------------------------------------------------------------------------------- 1 | "Title 1","Title 2","Title 3","Title 4" 2 | 1,"a","08/01/07","å" 3 | 2,"b","08/02/07","∫" 4 | 3,"c","08/03/07","ç" 5 | -------------------------------------------------------------------------------- /datetime/datetime_date_minmax.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Minimum and maximum values for dates. 7 | """ 8 | 9 | #end_pymotw_header 10 | import datetime 11 | 12 | print('Earliest :', datetime.date.min) 13 | print('Latest :', datetime.date.max) 14 | print('Resolution:', datetime.date.resolution) 15 | -------------------------------------------------------------------------------- /datetime/datetime_date_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Creating dates from existing objects. 7 | """ 8 | 9 | #end_pymotw_header 10 | import datetime 11 | 12 | d1 = datetime.date(2008, 3, 29) 13 | print('d1:', d1.ctime()) 14 | 15 | d2 = d1.replace(year=2009) 16 | print('d2:', d2.ctime()) 17 | -------------------------------------------------------------------------------- /datetime/datetime_datetime_combine.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import datetime 11 | 12 | t = datetime.time(1, 2, 3) 13 | print('t :', t) 14 | 15 | d = datetime.date.today() 16 | print('d :', d) 17 | 18 | dt = datetime.datetime.combine(d, t) 19 | print('dt:', dt) 20 | -------------------------------------------------------------------------------- /datetime/datetime_datetime_minmax.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """The range of valid datetime values. 7 | """ 8 | 9 | #end_pymotw_header 10 | import datetime 11 | 12 | print('Earliest :', datetime.datetime.min) 13 | print('Latest :', datetime.datetime.max) 14 | print('Resolution:', datetime.datetime.resolution) 15 | -------------------------------------------------------------------------------- /datetime/datetime_format.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import datetime 11 | 12 | today = datetime.datetime.today() 13 | print('ISO :', today) 14 | print('format(): {:%a %b %d %H:%M:%S %Y}'.format(today)) 15 | -------------------------------------------------------------------------------- /datetime/datetime_time_minmax.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Valid range of time values. 7 | """ 8 | 9 | #end_pymotw_header 10 | import datetime 11 | 12 | print('Earliest :', datetime.time.min) 13 | print('Latest :', datetime.time.max) 14 | print('Resolution:', datetime.time.resolution) 15 | -------------------------------------------------------------------------------- /datetime/datetime_time_resolution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Time resolution. 7 | """ 8 | 9 | #end_pymotw_header 10 | import datetime 11 | 12 | for m in [1, 0, 0.1, 0.6]: 13 | try: 14 | print('{:02.1f} :'.format(m), 15 | datetime.time(0, 0, 0, microsecond=m)) 16 | except TypeError as err: 17 | print('ERROR:', err) 18 | -------------------------------------------------------------------------------- /dbm/dbm_existing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import dbm 11 | 12 | with dbm.open('/tmp/example.db', 'r') as db: 13 | print('keys():', db.keys()) 14 | for k in db.keys(): 15 | print('iterating:', k, db[k]) 16 | print('db["author"] =', db['author']) 17 | -------------------------------------------------------------------------------- /dbm/dbm_intkeys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import dbm 11 | 12 | with dbm.open('/tmp/example.db', 'w') as db: 13 | try: 14 | db[1] = 'one' 15 | except TypeError as err: 16 | print(err) 17 | -------------------------------------------------------------------------------- /dbm/dbm_intvalue.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import dbm 11 | 12 | with dbm.open('/tmp/example.db', 'w') as db: 13 | try: 14 | db['one'] = 1 15 | except TypeError as err: 16 | print(err) 17 | -------------------------------------------------------------------------------- /dbm/dbm_new.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import dbm 11 | 12 | with dbm.open('/tmp/example.db', 'n') as db: 13 | db['key'] = 'value' 14 | db['today'] = 'Sunday' 15 | db['author'] = 'Doug' 16 | -------------------------------------------------------------------------------- /dbm/dbm_whichdb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import dbm 11 | 12 | print(dbm.whichdb('/tmp/example.db')) 13 | -------------------------------------------------------------------------------- /decimal/decimal_log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import decimal 11 | 12 | d = decimal.Decimal(100) 13 | print('d :', d) 14 | print('log10 :', d.log10()) 15 | print('ln :', d.ln()) 16 | -------------------------------------------------------------------------------- /decimal/decimal_precision.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import decimal 11 | 12 | d = decimal.Decimal('0.123456') 13 | 14 | for i in range(1, 5): 15 | decimal.getcontext().prec = i 16 | print(i, ':', d, d * 1) 17 | -------------------------------------------------------------------------------- /decimal/decimal_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import decimal 11 | 12 | # Tuple 13 | t = (1, (1, 1), -2) 14 | print('Input :', t) 15 | print('Decimal:', decimal.Decimal(t)) 16 | -------------------------------------------------------------------------------- /difflib/difflib_context.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Context diff example 6 | """ 7 | 8 | #end_pymotw_header 9 | import difflib 10 | from difflib_data import * 11 | 12 | diff = difflib.context_diff( 13 | text1_lines, 14 | text2_lines, 15 | lineterm='', 16 | ) 17 | print('\n'.join(diff)) 18 | -------------------------------------------------------------------------------- /difflib/difflib_differ.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Differ example 6 | """ 7 | 8 | 9 | #end_pymotw_header 10 | import difflib 11 | from difflib_data import * 12 | 13 | d = difflib.Differ() 14 | diff = d.compare(text1_lines, text2_lines) 15 | print('\n'.join(diff)) 16 | -------------------------------------------------------------------------------- /difflib/difflib_html.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """HtmlDiff example 6 | """ 7 | 8 | 9 | #end_pymotw_header 10 | import difflib 11 | from difflib_data import * 12 | 13 | d = difflib.HtmlDiff() 14 | print(d.make_table(text1_lines, text2_lines)) 15 | -------------------------------------------------------------------------------- /difflib/difflib_ndiff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """ndiff example 6 | """ 7 | 8 | #end_pymotw_header 9 | import difflib 10 | from difflib_data import * 11 | 12 | diff = difflib.ndiff(text1_lines, text2_lines) 13 | print('\n'.join(diff)) 14 | -------------------------------------------------------------------------------- /difflib/difflib_unified.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Unified diff example 6 | """ 7 | 8 | 9 | #end_pymotw_header 10 | import difflib 11 | from difflib_data import * 12 | 13 | diff = difflib.unified_diff( 14 | text1_lines, 15 | text2_lines, 16 | lineterm='', 17 | ) 18 | print('\n'.join(diff)) 19 | -------------------------------------------------------------------------------- /dis/dis_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | import dis 5 | 6 | 7 | class MyObject: 8 | """Example for dis.""" 9 | 10 | CLASS_ATTRIBUTE = 'some value' 11 | 12 | def __str__(self): 13 | return 'MyObject({})'.format(self.name) 14 | 15 | def __init__(self, name): 16 | self.name = name 17 | 18 | 19 | dis.dis(MyObject) 20 | -------------------------------------------------------------------------------- /dis/dis_constant_folding.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | # Folded 5 | i = 1 + 2 6 | f = 3.4 * 5.6 7 | s = 'Hello,' + ' World!' 8 | 9 | # Not folded 10 | I = i * 3 * 4 11 | F = f / 2 / 3 12 | S = s + '\n' + 'Fantastic!' 13 | -------------------------------------------------------------------------------- /dis/dis_faster_loop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | import string 5 | 6 | 7 | class Dictionary: 8 | 9 | def __init__(self, words): 10 | self.by_letter = { 11 | letter: [] 12 | for letter in string.ascii_letters 13 | } 14 | self.load_data(words) 15 | 16 | def load_data(self, words): 17 | for word in words: 18 | self.by_letter[word[0]].append(word) 19 | -------------------------------------------------------------------------------- /dis/dis_fastest_loop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | import collections 5 | 6 | 7 | class Dictionary: 8 | 9 | def __init__(self, words): 10 | self.by_letter = collections.defaultdict(list) 11 | self.load_data(words) 12 | 13 | def load_data(self, words): 14 | by_letter = self.by_letter 15 | for word in words: 16 | by_letter[word[0]].append(word) 17 | -------------------------------------------------------------------------------- /dis/dis_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | 5 | def f(*args): 6 | nargs = len(args) 7 | print(nargs, args) 8 | 9 | 10 | if __name__ == '__main__': 11 | import dis 12 | dis.dis(f) 13 | -------------------------------------------------------------------------------- /dis/dis_show_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | 5 | def f(*args): 6 | nargs = len(args) 7 | print(nargs, args) 8 | 9 | 10 | if __name__ == '__main__': 11 | import dis 12 | dis.show_code(f) 13 | -------------------------------------------------------------------------------- /dis/dis_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | my_dict = {'a': 1} 5 | -------------------------------------------------------------------------------- /dis/dis_slow_loop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | 5 | class Dictionary: 6 | 7 | def __init__(self, words): 8 | self.by_letter = {} 9 | self.load_data(words) 10 | 11 | def load_data(self, words): 12 | for word in words: 13 | try: 14 | self.by_letter[word[0]].append(word) 15 | except KeyError: 16 | self.by_letter[word[0]] = [word] 17 | -------------------------------------------------------------------------------- /dis/dis_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | 8 | #end_pymotw_header 9 | import dis 10 | 11 | code = """ 12 | my_dict = {'a': 1} 13 | """ 14 | 15 | print('Disassembly:\n') 16 | dis.dis(code) 17 | 18 | print('\nCode details:\n') 19 | dis.show_code(code) 20 | -------------------------------------------------------------------------------- /dis/dis_traceback.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | i = 1 5 | j = 0 6 | k = 3 7 | 8 | try: 9 | result = k * (i / j) + (i / k) 10 | except Exception: 11 | import dis 12 | import sys 13 | exc_type, exc_value, exc_tb = sys.exc_info() 14 | dis.distb(exc_tb) 15 | -------------------------------------------------------------------------------- /doctest/doctest_hashed_values.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Demonstrate how insertion order affects dictonaries and sets. 7 | """ 8 | 9 | #end_pymotw_header 10 | keys = ['a', 'aa', 'aaa'] 11 | 12 | print('dict:', {k: len(k) for k in keys}) 13 | print('set :', set(keys)) 14 | -------------------------------------------------------------------------------- /doctest/doctest_in_help.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Tests for this module are in the external help text. 7 | """ 8 | #end_pymotw_header 9 | def my_function(a, b): 10 | """Returns a*b 11 | """ 12 | return a * b 13 | -------------------------------------------------------------------------------- /doctest/doctest_private_tests_external.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | #end_pymotw_header 7 | """External tests associated with doctest_private_tests.py. 8 | 9 | >>> my_function(['A', 'B', 'C'], 2) 10 | ['A', 'B', 'C', 'A', 'B', 'C'] 11 | """ 12 | -------------------------------------------------------------------------------- /doctest/doctest_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Simple example using doctest 7 | """ 8 | 9 | #end_pymotw_header 10 | def my_function(a, b): 11 | """ 12 | >>> my_function(2, 3) 13 | 6 14 | >>> my_function('a', 3) 15 | 'aaa' 16 | """ 17 | return a * b 18 | -------------------------------------------------------------------------------- /doctest/doctest_testfile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Run the tests from an external file. 7 | """ 8 | 9 | #end_pymotw_header 10 | import doctest 11 | 12 | if __name__ == '__main__': 13 | doctest.testfile('doctest_in_help.txt') 14 | -------------------------------------------------------------------------------- /doctest/doctest_testmod_other_module.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Run tests for another module we import. 7 | """ 8 | 9 | #end_pymotw_header 10 | import doctest_simple 11 | 12 | if __name__ == '__main__': 13 | import doctest 14 | doctest.testmod(doctest_simple) 15 | -------------------------------------------------------------------------------- /enum/enum_intenum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import enum 8 | 9 | 10 | class BugStatus(enum.IntEnum): 11 | 12 | new = 7 13 | incomplete = 6 14 | invalid = 5 15 | wont_fix = 4 16 | in_progress = 3 17 | fix_committed = 2 18 | fix_released = 1 19 | 20 | 21 | print('Ordered by value:') 22 | print('\n'.join(' ' + s.name for s in sorted(BugStatus))) 23 | -------------------------------------------------------------------------------- /enum/enum_iterate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import enum 8 | 9 | 10 | class BugStatus(enum.Enum): 11 | 12 | new = 7 13 | incomplete = 6 14 | invalid = 5 15 | wont_fix = 4 16 | in_progress = 3 17 | fix_committed = 2 18 | fix_released = 1 19 | 20 | 21 | for status in BugStatus: 22 | print('{:15} = {}'.format(status.name, status.value)) 23 | -------------------------------------------------------------------------------- /enum/enum_unique_enforce.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import enum 8 | 9 | 10 | @enum.unique 11 | class BugStatus(enum.Enum): 12 | 13 | new = 7 14 | incomplete = 6 15 | invalid = 5 16 | wont_fix = 4 17 | in_progress = 3 18 | fix_committed = 2 19 | fix_released = 1 20 | 21 | # This will trigger an error with unique applied. 22 | by_design = 4 23 | closed = 1 24 | -------------------------------------------------------------------------------- /filecmp/filecmp_dircmp_diff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import filecmp 11 | 12 | dc = filecmp.dircmp('example/dir1', 'example/dir2') 13 | print('Same :', dc.same_files) 14 | print('Different :', dc.diff_files) 15 | print('Funny :', dc.funny_files) 16 | -------------------------------------------------------------------------------- /filecmp/filecmp_dircmp_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import filecmp 11 | import pprint 12 | 13 | dc = filecmp.dircmp('example/dir1', 'example/dir2') 14 | print('Left:') 15 | pprint.pprint(dc.left_list) 16 | 17 | print('\nRight:') 18 | pprint.pprint(dc.right_list) 19 | -------------------------------------------------------------------------------- /filecmp/filecmp_dircmp_report.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import filecmp 11 | 12 | dc = filecmp.dircmp('example/dir1', 'example/dir2') 13 | dc.report() 14 | -------------------------------------------------------------------------------- /filecmp/filecmp_dircmp_report_full_closure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import filecmp 11 | 12 | dc = filecmp.dircmp('example/dir1', 'example/dir2') 13 | dc.report_full_closure() 14 | -------------------------------------------------------------------------------- /filecmp/filecmp_dircmp_subdirs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import filecmp 11 | 12 | dc = filecmp.dircmp('example/dir1', 'example/dir2') 13 | print('Subdirectories:') 14 | print(dc.subdirs) 15 | -------------------------------------------------------------------------------- /fileinput/etc_hosts.txt: -------------------------------------------------------------------------------- 1 | ## 2 | # Host Database 3 | # 4 | # localhost is used to configure the loopback interface 5 | # when the system is booting. Do not change this entry. 6 | ## 7 | 127.0.0.1 localhost 8 | 255.255.255.255 broadcasthost 9 | ::1 localhost 10 | fe80::1%lo0 localhost 11 | 10.17.177.128 hubert hubert.hellfly.net 12 | 10.17.177.132 cubert cubert.hellfly.net 13 | 10.17.177.136 zoidberg zoidberg.hellfly.net 14 | -------------------------------------------------------------------------------- /fnmatch/fnmatch_translate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Translate a glob-style pattern to a regular expression. 7 | """ 8 | 9 | #end_pymotw_header 10 | import fnmatch 11 | 12 | pattern = 'fnmatch_*.py' 13 | print('Pattern :', pattern) 14 | print('Regex :', fnmatch.translate(pattern)) 15 | -------------------------------------------------------------------------------- /fractions/fractions_create_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import fractions 11 | 12 | for n, d in [(1, 2), (2, 4), (3, 6)]: 13 | f = fractions.Fraction(n, d) 14 | print('{}/{} = {}'.format(n, d, f)) 15 | -------------------------------------------------------------------------------- /fractions/fractions_create_strings.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import fractions 11 | 12 | for s in ['1/2', '2/4', '3/6']: 13 | f = fractions.Fraction(s) 14 | print('{} = {}'.format(s, f)) 15 | -------------------------------------------------------------------------------- /fractions/fractions_create_strings_floats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import fractions 11 | 12 | for s in ['0.5', '1.5', '2.0', '5e-1']: 13 | f = fractions.Fraction(s) 14 | print('{0:>4} = {1}'.format(s, f)) 15 | -------------------------------------------------------------------------------- /fractions/fractions_from_float.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import fractions 11 | 12 | for v in [0.1, 0.5, 1.5, 2.0]: 13 | print('{} = {}'.format(v, fractions.Fraction(v))) 14 | -------------------------------------------------------------------------------- /functools/functools_reduce.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import functools 8 | 9 | 10 | def do_reduce(a, b): 11 | print('do_reduce({}, {})'.format(a, b)) 12 | return a + b 13 | 14 | 15 | data = range(1, 5) 16 | print(data) 17 | result = functools.reduce(do_reduce, data) 18 | print('result: {}'.format(result)) 19 | -------------------------------------------------------------------------------- /functools/functools_reduce_initializer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import functools 8 | 9 | 10 | def do_reduce(a, b): 11 | print('do_reduce({}, {})'.format(a, b)) 12 | return a + b 13 | 14 | 15 | data = range(1, 5) 16 | print(data) 17 | result = functools.reduce(do_reduce, data, 99) 18 | print('result: {}'.format(result)) 19 | -------------------------------------------------------------------------------- /gc/gc_debug_stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Tuning the garbage collector threshold. 7 | """ 8 | 9 | #end_pymotw_header 10 | import gc 11 | 12 | gc.set_debug(gc.DEBUG_STATS) 13 | 14 | gc.collect() 15 | print('Exiting') 16 | -------------------------------------------------------------------------------- /gc/gc_get_objects.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Examine the objects being managed. 7 | """ 8 | 9 | #end_pymotw_header 10 | import gc 11 | 12 | print(len(gc.get_objects())) 13 | -------------------------------------------------------------------------------- /gc/gc_get_threshold.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Show the default thresholds. 7 | """ 8 | 9 | #end_pymotw_header 10 | import gc 11 | 12 | print(gc.get_threshold()) 13 | -------------------------------------------------------------------------------- /getopt/getopt_long.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using getopt with longer option names. 3 | """ 4 | 5 | #end_pymotw_header 6 | import getopt 7 | 8 | opts, args = getopt.getopt( 9 | ['--noarg', 10 | '--witharg', 'val', 11 | '--witharg2=another'], 12 | '', 13 | ['noarg', 'witharg=', 'witharg2='], 14 | ) 15 | for opt in opts: 16 | print(opt) 17 | -------------------------------------------------------------------------------- /getopt/getopt_short.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using optparse with single-letter options. 3 | """ 4 | 5 | #end_pymotw_header 6 | import getopt 7 | 8 | opts, args = getopt.getopt(['-a', '-bval', '-c', 'val'], 'ab:c:') 9 | 10 | for opt in opts: 11 | print(opt) 12 | -------------------------------------------------------------------------------- /getpass/getpass_defaults.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright 2007 Doug Hellmann. 5 | # 6 | """Default use of getpass. 7 | """ 8 | 9 | #end_pymotw_header 10 | import getpass 11 | 12 | try: 13 | p = getpass.getpass() 14 | except Exception as err: 15 | print('ERROR:', err) 16 | else: 17 | print('You entered:', p) 18 | -------------------------------------------------------------------------------- /getpass/getpass_noterminal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright 2007 Doug Hellmann. 5 | # 6 | """Using read() when there is no tty for getpass() to use. 7 | 8 | """ 9 | 10 | #end_pymotw_header 11 | import getpass 12 | import sys 13 | 14 | if sys.stdin.isatty(): 15 | p = getpass.getpass('Using getpass: ') 16 | else: 17 | print('Using readline') 18 | p = sys.stdin.readline().rstrip() 19 | 20 | print('Read: ', p) 21 | -------------------------------------------------------------------------------- /getpass/getpass_prompt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright 2007 Doug Hellmann. 5 | # 6 | """Passing a prompt to getpass. 7 | 8 | """ 9 | 10 | #end_pymotw_header 11 | import getpass 12 | 13 | p = getpass.getpass(prompt='What is your favorite color? ') 14 | if p.lower() == 'blue': 15 | print('Right. Off you go.') 16 | else: 17 | print('Auuuuugh!') 18 | -------------------------------------------------------------------------------- /getpass/getpass_stream.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright 2007 Doug Hellmann. 5 | # 6 | """Using sys.stderr for the prompt lets us redirect stdout. 7 | 8 | """ 9 | 10 | #end_pymotw_header 11 | import getpass 12 | import sys 13 | 14 | p = getpass.getpass(stream=sys.stderr) 15 | print('You entered:', p) 16 | -------------------------------------------------------------------------------- /gettext/gettext_app_builtin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | # flake8: noqa 9 | 10 | #end_pymotw_header 11 | import gettext 12 | 13 | gettext.install( 14 | 'example', 15 | 'locale', 16 | names=['ngettext'], 17 | ) 18 | 19 | print(_('This message is in the script.')) 20 | -------------------------------------------------------------------------------- /gettext/gettext_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import gettext 11 | 12 | # Set up message catalog access 13 | t = gettext.translation( 14 | 'example_domain', 'locale', 15 | fallback=True, 16 | ) 17 | _ = t.gettext 18 | 19 | print(_('This message is in the script.')) 20 | -------------------------------------------------------------------------------- /gettext/gettext_example_corrected.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import gettext 11 | 12 | # Set up message catalog access 13 | t = gettext.translation( 14 | 'example', 'locale', 15 | fallback=True, 16 | ) 17 | _ = t.gettext 18 | 19 | print(_('This message is in the script.')) 20 | -------------------------------------------------------------------------------- /gettext/gettext_find.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import gettext 11 | 12 | catalogs = gettext.find('example', 'locale', all=True) 13 | print('Catalogs:', catalogs) 14 | -------------------------------------------------------------------------------- /gettext/gettext_module_global.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import gettext 11 | 12 | t = gettext.translation( 13 | 'example', 14 | 'locale', 15 | fallback=False, 16 | ) 17 | _ = t.gettext 18 | ngettext = t.ngettext 19 | 20 | print(_('This message is in the script.')) 21 | -------------------------------------------------------------------------------- /glob/dir/file.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /glob/dir/file1.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /glob/dir/file2.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /glob/dir/file[.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /glob/dir/file_.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /glob/dir/filea.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /glob/dir/fileb.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /glob/dir/subdir/subfile.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /gzip/gzip_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import gzip 11 | import io 12 | 13 | with gzip.open('example.txt.gz', 'rb') as input_file: 14 | with io.TextIOWrapper(input_file, encoding='utf-8') as dec: 15 | print(dec.read()) 16 | -------------------------------------------------------------------------------- /hashlib/hashlib_algorithms.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import hashlib 8 | 9 | 10 | print('Guaranteed:\n{}\n'.format( 11 | ', '.join(sorted(hashlib.algorithms_guaranteed)))) 12 | print('Available:\n{}'.format( 13 | ', '.join(sorted(hashlib.algorithms_available)))) 14 | -------------------------------------------------------------------------------- /hashlib/hashlib_md5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Simple MD5 generation. 7 | """ 8 | 9 | #end_pymotw_header 10 | import hashlib 11 | 12 | from hashlib_data import lorem 13 | 14 | h = hashlib.md5() 15 | h.update(lorem.encode('utf-8')) 16 | print(h.hexdigest()) 17 | -------------------------------------------------------------------------------- /hashlib/hashlib_sha1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Simple SHA1 generation. 7 | """ 8 | 9 | #end_pymotw_header 10 | import hashlib 11 | 12 | from hashlib_data import lorem 13 | 14 | h = hashlib.sha1() 15 | h.update(lorem.encode('utf-8')) 16 | print(h.hexdigest()) 17 | -------------------------------------------------------------------------------- /heapq/heapq_heapdata.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | # This data was generated with the random module. 11 | 12 | data = [19, 9, 4, 10, 11] 13 | -------------------------------------------------------------------------------- /heapq/heapq_heapify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import heapq 11 | from heapq_showtree import show_tree 12 | from heapq_heapdata import data 13 | 14 | print('random :', data) 15 | heapq.heapify(data) 16 | print('heapified :') 17 | show_tree(data) 18 | -------------------------------------------------------------------------------- /heapq/heapq_heappush.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import heapq 11 | from heapq_showtree import show_tree 12 | from heapq_heapdata import data 13 | 14 | heap = [] 15 | print('random :', data) 16 | print() 17 | 18 | for n in data: 19 | print('add {:>3}:'.format(n)) 20 | heapq.heappush(heap, n) 21 | show_tree(heap) 22 | -------------------------------------------------------------------------------- /hmac/hmac_base64.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Generate a base64 encoded HMAC signature. 3 | """ 4 | 5 | #end_pymotw_header 6 | import base64 7 | import hmac 8 | import hashlib 9 | 10 | with open('lorem.txt', 'rb') as f: 11 | body = f.read() 12 | 13 | hash = hmac.new( 14 | b'secret-shared-key-goes-here', 15 | body, 16 | hashlib.sha1, 17 | ) 18 | 19 | digest = hash.digest() 20 | print(base64.encodebytes(digest)) 21 | -------------------------------------------------------------------------------- /hmac/hmac_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Generate a simple HMAC signature. 3 | """ 4 | 5 | #end_pymotw_header 6 | import hmac 7 | 8 | digest_maker = hmac.new(b'secret-shared-key-goes-here') 9 | 10 | with open('lorem.txt', 'rb') as f: 11 | while True: 12 | block = f.read(1024) 13 | if not block: 14 | break 15 | digest_maker.update(block) 16 | 17 | digest = digest_maker.hexdigest() 18 | print(digest) 19 | -------------------------------------------------------------------------------- /http.cookies/http_cookies_js_output.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | from http import cookies 12 | import textwrap 13 | 14 | 15 | c = cookies.SimpleCookie() 16 | c['mycookie'] = 'cookie_value' 17 | c['another_cookie'] = 'second value' 18 | js_text = c.js_output() 19 | print(textwrap.dedent(js_text).lstrip()) 20 | -------------------------------------------------------------------------------- /http.cookies/http_cookies_setheaders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | from http import cookies 12 | 13 | 14 | c = cookies.SimpleCookie() 15 | c['mycookie'] = 'cookie_value' 16 | print(c) 17 | -------------------------------------------------------------------------------- /imaplib/imaplib_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import imaplib 11 | from pprint import pprint 12 | from imaplib_connect import open_connection 13 | 14 | with open_connection() as c: 15 | typ, data = c.list() 16 | print('Response code:', typ) 17 | print('Response:') 18 | pprint(data) 19 | -------------------------------------------------------------------------------- /imaplib/imaplib_list_pattern.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import imaplib 11 | 12 | from imaplib_connect import open_connection 13 | 14 | with open_connection() as c: 15 | typ, data = c.list(pattern='*Example*') 16 | 17 | print('Response code:', typ) 18 | 19 | for line in data: 20 | print('Server response:', line) 21 | -------------------------------------------------------------------------------- /imaplib/imaplib_list_subfolders.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import imaplib 11 | 12 | from imaplib_connect import open_connection 13 | 14 | with open_connection() as c: 15 | typ, data = c.list(directory='Example') 16 | 17 | print('Response code:', typ) 18 | 19 | for line in data: 20 | print('Server response:', line) 21 | -------------------------------------------------------------------------------- /imaplib/imaplib_select.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import imaplib 11 | import imaplib_connect 12 | 13 | with imaplib_connect.open_connection() as c: 14 | typ, data = c.select('INBOX') 15 | print(typ, data) 16 | num_msgs = int(data[0]) 17 | print('There are {} messages in INBOX'.format(num_msgs)) 18 | -------------------------------------------------------------------------------- /imaplib/imaplib_select_invalid.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import imaplib 11 | import imaplib_connect 12 | 13 | with imaplib_connect.open_connection() as c: 14 | typ, data = c.select('Does-Not-Exist') 15 | print(typ, data) 16 | -------------------------------------------------------------------------------- /importlib/example/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | print('Importing example package') 11 | -------------------------------------------------------------------------------- /importlib/example/submodule.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | print('Importing submodule') 11 | -------------------------------------------------------------------------------- /importlib/importlib_find_loader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import importlib 8 | 9 | spec = importlib.util.find_spec('example') 10 | print('Loader:', spec.loader) 11 | 12 | m = spec.loader.load_module() 13 | print('Module:', m) 14 | -------------------------------------------------------------------------------- /importlib/importlib_import_module_error.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Importing a module from a package 8 | """ 9 | 10 | #end_pymotw_header 11 | import importlib 12 | 13 | 14 | try: 15 | importlib.import_module('example.nosuchmodule') 16 | except ImportError as err: 17 | print('Error:', err) 18 | -------------------------------------------------------------------------------- /importlib/importlib_reload.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Importing a module from a package 8 | """ 9 | 10 | #end_pymotw_header 11 | import importlib 12 | 13 | 14 | m1 = importlib.import_module('example.submodule') 15 | print(m1) 16 | 17 | m2 = importlib.reload(m1) 18 | print(m1 is m2) 19 | -------------------------------------------------------------------------------- /importlib/importlib_submodule.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import importlib 8 | 9 | spec = importlib.util.find_spec('.submodule', package='example') 10 | print('Loader:', spec.loader) 11 | 12 | m = spec.loader.load_module() 13 | print('Module:', m) 14 | -------------------------------------------------------------------------------- /inspect/inspect_formatargspec.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Print information about the arguments to a method. 3 | """ 4 | 5 | 6 | #end_pymotw_header 7 | import inspect 8 | import example 9 | 10 | spec = inspect.getargspec(example.module_level_function) 11 | print(spec) 12 | print(inspect.formatargspec(spec)) 13 | -------------------------------------------------------------------------------- /inspect/inspect_getclasstree_unique.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | import example 8 | from inspect_getclasstree import * 9 | 10 | print_class_tree(inspect.getclasstree( 11 | [example.A, example.B, C, D], 12 | unique=True, 13 | )) 14 | -------------------------------------------------------------------------------- /inspect/inspect_getcomments_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Show the comment before a method. 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | import example 8 | 9 | print(inspect.getcomments(example.B.do_something)) 10 | -------------------------------------------------------------------------------- /inspect/inspect_getcomments_module.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Show the comment before a method. 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | import example 8 | 9 | print(inspect.getcomments(example)) 10 | -------------------------------------------------------------------------------- /inspect/inspect_getdoc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Docstrings 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | import example 8 | 9 | print('B.__doc__:') 10 | print(example.B.__doc__) 11 | print() 12 | print('getdoc(B):') 13 | print(inspect.getdoc(example.B)) 14 | -------------------------------------------------------------------------------- /inspect/inspect_getmembers_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using getmembers() 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | from pprint import pprint 8 | 9 | import example 10 | 11 | pprint(inspect.getmembers(example.A), width=65) 12 | -------------------------------------------------------------------------------- /inspect/inspect_getmembers_class_methods.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using getmembers() 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | from pprint import pprint 8 | 9 | import example 10 | 11 | pprint(inspect.getmembers(example.A, inspect.isfunction)) 12 | -------------------------------------------------------------------------------- /inspect/inspect_getmembers_class_methods_b.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using getmembers() 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | from pprint import pprint 8 | 9 | import example 10 | 11 | pprint(inspect.getmembers(example.B, inspect.isfunction)) 12 | -------------------------------------------------------------------------------- /inspect/inspect_getmembers_instance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using getmembers() 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | from pprint import pprint 8 | 9 | import example 10 | 11 | a = example.A(name='inspect_getmembers') 12 | pprint(inspect.getmembers(a, inspect.ismethod)) 13 | -------------------------------------------------------------------------------- /inspect/inspect_getmembers_module.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using getmembers() 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | 8 | import example 9 | 10 | for name, data in inspect.getmembers(example): 11 | if name.startswith('__'): 12 | continue 13 | print('{} : {!r}'.format(name, data)) 14 | -------------------------------------------------------------------------------- /inspect/inspect_getmembers_module_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using getmembers() 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | 8 | import example 9 | 10 | for name, data in inspect.getmembers(example, inspect.isclass): 11 | print('{} : {!r}'.format(name, data)) 12 | -------------------------------------------------------------------------------- /inspect/inspect_getsource_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | import example 8 | 9 | print(inspect.getsource(example.A)) 10 | -------------------------------------------------------------------------------- /inspect/inspect_getsource_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | import example 8 | 9 | print(inspect.getsource(example.A.get_name)) 10 | -------------------------------------------------------------------------------- /inspect/inspect_getsourcelines_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | """ 4 | 5 | #end_pymotw_header 6 | import inspect 7 | import pprint 8 | import example 9 | 10 | pprint.pprint(inspect.getsourcelines(example.A.get_name)) 11 | -------------------------------------------------------------------------------- /itertools/itertools_accumulate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """combine values 4 | """ 5 | 6 | #end_pymotw_header 7 | from itertools import * 8 | 9 | print(list(accumulate(range(5)))) 10 | print(list(accumulate('abcde'))) 11 | -------------------------------------------------------------------------------- /itertools/itertools_accumulate_custom.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """combine values 4 | """ 5 | 6 | #end_pymotw_header 7 | from itertools import * 8 | 9 | 10 | def f(a, b): 11 | print(a, b) 12 | return b + a + b 13 | 14 | 15 | print(list(accumulate('abcde', f))) 16 | -------------------------------------------------------------------------------- /itertools/itertools_chain.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using chain() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | for i in chain([1, 2, 3], ['a', 'b', 'c']): 9 | print(i, end=' ') 10 | print() 11 | -------------------------------------------------------------------------------- /itertools/itertools_chain_from_iterable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using chain() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | 9 | def make_iterables_to_chain(): 10 | yield [1, 2, 3] 11 | yield ['a', 'b', 'c'] 12 | 13 | 14 | for i in chain.from_iterable(make_iterables_to_chain()): 15 | print(i, end=' ') 16 | print() 17 | -------------------------------------------------------------------------------- /itertools/itertools_compress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using filter() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | every_third = cycle([False, False, True]) 9 | data = range(1, 10) 10 | 11 | for i in compress(data, every_third): 12 | print(i, end=' ') 13 | print() 14 | -------------------------------------------------------------------------------- /itertools/itertools_count.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using count() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | for i in zip(count(1), ['a', 'b', 'c']): 9 | print(i) 10 | -------------------------------------------------------------------------------- /itertools/itertools_count_step.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using count() 3 | """ 4 | 5 | #end_pymotw_header 6 | import fractions 7 | from itertools import * 8 | 9 | start = fractions.Fraction(1, 3) 10 | step = fractions.Fraction(1, 3) 11 | 12 | for i in zip(count(start, step), ['a', 'b', 'c']): 13 | print('{}: {}'.format(*i)) 14 | -------------------------------------------------------------------------------- /itertools/itertools_cycle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using cycle(). 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | for i in zip(range(7), cycle(['a', 'b', 'c'])): 9 | print(i) 10 | -------------------------------------------------------------------------------- /itertools/itertools_dropwhile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using dropwhile() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | 9 | def should_drop(x): 10 | print('Testing:', x) 11 | return x < 1 12 | 13 | 14 | for i in dropwhile(should_drop, [-1, 0, 1, 2, -2]): 15 | print('Yielding:', i) 16 | -------------------------------------------------------------------------------- /itertools/itertools_filter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using filter() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | 9 | def check_item(x): 10 | print('Testing:', x) 11 | return x < 1 12 | 13 | 14 | for i in filter(check_item, [-1, 0, 1, 2, -2]): 15 | print('Yielding:', i) 16 | -------------------------------------------------------------------------------- /itertools/itertools_filterfalse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using filterfalse() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | 9 | def check_item(x): 10 | print('Testing:', x) 11 | return x < 1 12 | 13 | 14 | for i in filterfalse(check_item, [-1, 0, 1, 2, -2]): 15 | print('Yielding:', i) 16 | -------------------------------------------------------------------------------- /itertools/itertools_groupby.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using groupby() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | from operator import itemgetter 8 | 9 | d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) 10 | di = sorted(d.iteritems(), key=itemgetter(1)) 11 | for k, g in groupby(di, key=itemgetter(1)): 12 | print(k, map(itemgetter(0), g)) 13 | -------------------------------------------------------------------------------- /itertools/itertools_repeat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using repeat() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | for i in repeat('over-and-over', 5): 9 | print(i) 10 | -------------------------------------------------------------------------------- /itertools/itertools_repeat_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using repeat() and map() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | for i in map(lambda x, y: (x, y, x * y), repeat(2), range(5)): 9 | print('{:d} * {:d} = {:d}'.format(*i)) 10 | -------------------------------------------------------------------------------- /itertools/itertools_repeat_zip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using repeat() with zip(). 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | for i, s in zip(count(), repeat('over-and-over', 5)): 9 | print(i, s) 10 | -------------------------------------------------------------------------------- /itertools/itertools_starmap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using starmap() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | values = [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)] 9 | 10 | for i in starmap(lambda x, y: (x, y, x * y), values): 11 | print('{} * {} = {}'.format(*i)) 12 | -------------------------------------------------------------------------------- /itertools/itertools_takewhile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using takewhile() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | 9 | def should_take(x): 10 | print('Testing:', x) 11 | return x < 2 12 | 13 | 14 | for i in takewhile(should_take, [-1, 0, 1, 2, -2]): 15 | print('Yielding:', i) 16 | -------------------------------------------------------------------------------- /itertools/itertools_tee.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using tee() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | r = islice(count(), 5) 9 | i1, i2 = tee(r) 10 | 11 | print('i1:', list(i1)) 12 | print('i2:', list(i2)) 13 | -------------------------------------------------------------------------------- /itertools/itertools_tee_error.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using tee() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | r = islice(count(), 5) 9 | i1, i2 = tee(r) 10 | 11 | print('r:', end=' ') 12 | for i in r: 13 | print(i, end=' ') 14 | if i > 1: 15 | break 16 | print() 17 | 18 | print('i1:', list(i1)) 19 | print('i2:', list(i2)) 20 | -------------------------------------------------------------------------------- /itertools/itertools_zip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using zip() 3 | """ 4 | 5 | #end_pymotw_header 6 | for i in zip([1, 2, 3], ['a', 'b', 'c']): 7 | print(i) 8 | -------------------------------------------------------------------------------- /itertools/itertools_zip_longest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using zip() 3 | """ 4 | 5 | #end_pymotw_header 6 | from itertools import * 7 | 8 | r1 = range(3) 9 | r2 = range(2) 10 | 11 | print('zip stops early:') 12 | print(list(zip(r1, r2))) 13 | 14 | r1 = range(3) 15 | r2 = range(2) 16 | 17 | print('\nzip_longest processes all of the values:') 18 | print(list(zip_longest(r1, r2))) 19 | -------------------------------------------------------------------------------- /json/json_dump_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import io 11 | import json 12 | 13 | data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}] 14 | 15 | f = io.StringIO() 16 | json.dump(data, f) 17 | 18 | print(f.getvalue()) 19 | -------------------------------------------------------------------------------- /json/json_encoder_iterable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import json 11 | 12 | encoder = json.JSONEncoder() 13 | data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}] 14 | 15 | for part in encoder.iterencode(data): 16 | print('PART:', part) 17 | -------------------------------------------------------------------------------- /json/json_indent.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import json 11 | 12 | data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}] 13 | print('DATA:', repr(data)) 14 | 15 | print('NORMAL:', json.dumps(data, sort_keys=True)) 16 | print('INDENT:', json.dumps(data, sort_keys=True, indent=2)) 17 | -------------------------------------------------------------------------------- /json/json_load_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import io 11 | import json 12 | 13 | f = io.StringIO('[{"a": "A", "c": 3.0, "b": [2, 4]}]') 14 | print(json.load(f)) 15 | -------------------------------------------------------------------------------- /json/json_myobj.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | 11 | class MyObj: 12 | 13 | def __init__(self, s): 14 | self.s = s 15 | 16 | def __repr__(self): 17 | return ''.format(self.s) 18 | -------------------------------------------------------------------------------- /json/json_simple_types.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import json 11 | 12 | data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}] 13 | print('DATA:', repr(data)) 14 | 15 | data_string = json.dumps(data) 16 | print('JSON:', data_string) 17 | -------------------------------------------------------------------------------- /linecache/linecache_empty_line.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Example use of linecache module. 3 | """ 4 | 5 | #end_pymotw_header 6 | import linecache 7 | from linecache_data import * 8 | 9 | filename = make_tempfile() 10 | 11 | # Blank lines include the newline 12 | print('BLANK : {!r}'.format(linecache.getline(filename, 8))) 13 | 14 | cleanup(filename) 15 | -------------------------------------------------------------------------------- /linecache/linecache_missing_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import linecache 12 | 13 | # Errors are even hidden if linecache cannot find the file 14 | no_such_file = linecache.getline( 15 | 'this_file_does_not_exist.txt', 1, 16 | ) 17 | print('NO FILE: {!r}'.format(no_such_file)) 18 | -------------------------------------------------------------------------------- /logging/logging_capture_warnings.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Simple logging to stderr using different levels. 3 | """ 4 | 5 | #end_pymotw_header 6 | import logging 7 | import warnings 8 | 9 | logging.basicConfig( 10 | level=logging.INFO, 11 | ) 12 | 13 | warnings.warn('This warning is not sent to the logs') 14 | 15 | logging.captureWarnings(True) 16 | 17 | warnings.warn('This warning is sent to the logs') 18 | -------------------------------------------------------------------------------- /mailbox/mailbox_maildir_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import mailbox 11 | 12 | mbox = mailbox.Maildir('Example') 13 | for message in mbox: 14 | print(message['subject']) 15 | -------------------------------------------------------------------------------- /mailbox/mailbox_mbox_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import mailbox 11 | 12 | mbox = mailbox.mbox('example.mbox') 13 | for message in mbox: 14 | print(message['subject']) 15 | -------------------------------------------------------------------------------- /math/math_constants.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Constants in the math module. 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print(' π: {:.30f}'.format(math.pi)) 13 | print(' e: {:.30f}'.format(math.e)) 14 | print('nan: {:.30f}'.format(math.nan)) 15 | print('inf: {:.30f}'.format(math.inf)) 16 | -------------------------------------------------------------------------------- /math/math_erf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Gauss Error Function 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print('{:^5} {:7}'.format('x', 'erf(x)')) 13 | print('{:-^5} {:-^7}'.format('', '')) 14 | 15 | for x in [-3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3]: 16 | print('{:5.2f} {:7.4f}'.format(x, math.erf(x))) 17 | -------------------------------------------------------------------------------- /math/math_erfc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Gauss Error Function 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print('{:^5} {:7}'.format('x', 'erfc(x)')) 13 | print('{:-^5} {:-^7}'.format('', '')) 14 | 15 | for x in [-3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3]: 16 | print('{:5.2f} {:7.4f}'.format(x, math.erfc(x))) 17 | -------------------------------------------------------------------------------- /math/math_exp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Raise e to a power. 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | x = 2 13 | 14 | fmt = '{:.20f}' 15 | print(fmt.format(math.e ** 2)) 16 | print(fmt.format(math.pow(math.e, 2))) 17 | print(fmt.format(math.exp(2))) 18 | -------------------------------------------------------------------------------- /math/math_expm1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Logarithms close to zero. 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | x = 0.0000000000000000000000001 13 | 14 | print(x) 15 | print(math.exp(x) - 1) 16 | print(math.expm1(x)) 17 | -------------------------------------------------------------------------------- /math/math_fabs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Absolute value 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print(math.fabs(-1.1)) 13 | print(math.fabs(-0.0)) 14 | print(math.fabs(0.0)) 15 | print(math.fabs(1.1)) 16 | -------------------------------------------------------------------------------- /math/math_factorial.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Factorial 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | for i in [0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.1]: 13 | try: 14 | print('{:2.0f} {:6.0f}'.format(i, math.factorial(i))) 15 | except ValueError as err: 16 | print('Error computing factorial({}): {}'.format(i, err)) 17 | -------------------------------------------------------------------------------- /math/math_frexp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Separate mantissa from exponent. 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print('{:^7} {:^7} {:^7}'.format('x', 'm', 'e')) 13 | print('{:-^7} {:-^7} {:-^7}'.format('', '', '')) 14 | 15 | for x in [0.1, 0.5, 4.0]: 16 | m, e = math.frexp(x) 17 | print('{:7.2f} {:7.2f} {:7d}'.format(x, m, e)) 18 | -------------------------------------------------------------------------------- /math/math_gamma.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Factorial 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | for i in [0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]: 13 | try: 14 | print('{:2.1f} {:6.2f}'.format(i, math.gamma(i))) 15 | except ValueError as err: 16 | print('Error computing gamma({}): {}'.format(i, err)) 17 | -------------------------------------------------------------------------------- /math/math_gcd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Greatest common denominator 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print(math.gcd(10, 8)) 13 | print(math.gcd(10, 0)) 14 | print(math.gcd(50, 225)) 15 | print(math.gcd(11, 9)) 16 | print(math.gcd(0, 0)) 17 | -------------------------------------------------------------------------------- /math/math_isfinite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Checking for overflow or infinite values. 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | for f in [0.0, 1.0, math.pi, math.e, math.inf, math.nan]: 13 | print('{:5.2f} {!s}'.format(f, math.isfinite(f))) 14 | -------------------------------------------------------------------------------- /math/math_log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Logarithms 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print(math.log(8)) 13 | print(math.log(8, 2)) 14 | print(math.log(0.5, 2)) 15 | -------------------------------------------------------------------------------- /math/math_log1p.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Logarithms close to zero. 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | x = 0.0000000000000000000000001 13 | print('x :', x) 14 | print('1 + x :', 1 + x) 15 | print('log(1+x):', math.log(1 + x)) 16 | print('log1p(x):', math.log1p(x)) 17 | -------------------------------------------------------------------------------- /math/math_modf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Split fractional from whole number part. 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | for i in range(6): 13 | print('{}/2 = {}'.format(i, math.modf(i / 2.0))) 14 | -------------------------------------------------------------------------------- /math/math_overflow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """OverflowError 7 | """ 8 | 9 | #end_pymotw_header 10 | x = 10.0 ** 200 11 | 12 | print('x =', x) 13 | print('x*x =', x * x) 14 | print('x**2 =', end=' ') 15 | try: 16 | print(x ** 2) 17 | except OverflowError as err: 18 | print(err) 19 | -------------------------------------------------------------------------------- /math/math_sqrt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Square roots 7 | """ 8 | 9 | #end_pymotw_header 10 | import math 11 | 12 | print(math.sqrt(9.0)) 13 | print(math.sqrt(3)) 14 | try: 15 | print(math.sqrt(-1)) 16 | except ValueError as err: 17 | print('Cannot compute sqrt(-1):', err) 18 | -------------------------------------------------------------------------------- /multiprocessing/multiprocessing_import_worker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Creating and waiting for a process 7 | """ 8 | #end_pymotw_header 9 | def worker(): 10 | """worker function""" 11 | print('Worker') 12 | return 13 | -------------------------------------------------------------------------------- /operator/operator_comparisons.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | from operator import * 11 | 12 | a = 1 13 | b = 5.0 14 | 15 | print('a =', a) 16 | print('b =', b) 17 | for func in (lt, le, eq, ne, ge, gt): 18 | print('{}(a, b): {}'.format(func.__name__, func(a, b))) 19 | -------------------------------------------------------------------------------- /os.path/ospath_expanduser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Expand tilde in filenames. 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import os.path 12 | 13 | for user in ['', 'dhellmann', 'nosuchuser']: 14 | lookup = '~' + user 15 | print('{!r:>15} : {!r}'.format( 16 | lookup, os.path.expanduser(lookup))) 17 | -------------------------------------------------------------------------------- /os.path/ospath_expandvars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Expand shell variables in filenames. 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import os.path 12 | import os 13 | 14 | os.environ['MYVAR'] = 'VALUE' 15 | 16 | print(os.path.expandvars('/path/to/$MYVAR')) 17 | -------------------------------------------------------------------------------- /os.path/ospath_normpath.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Compute a "normalized" path. 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import os.path 12 | 13 | PATHS = [ 14 | 'one//two//three', 15 | 'one/./two/./three', 16 | 'one/../alt/two/three', 17 | ] 18 | 19 | for path in PATHS: 20 | print('{!r:>22} : {!r}'.format(path, os.path.normpath(path))) 21 | -------------------------------------------------------------------------------- /os/os_access.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Check access rights on a file 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | print('Testing:', __file__) 9 | print('Exists:', os.access(__file__, os.F_OK)) 10 | print('Readable:', os.access(__file__, os.R_OK)) 11 | print('Writable:', os.access(__file__, os.W_OK)) 12 | print('Executable:', os.access(__file__, os.X_OK)) 13 | -------------------------------------------------------------------------------- /os/os_cwd_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using the os module to read and write environment variables. 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | print('Starting:', os.getcwd()) 9 | 10 | print('Moving up one:', os.pardir) 11 | os.chdir(os.pardir) 12 | 13 | print('After move:', os.getcwd()) 14 | -------------------------------------------------------------------------------- /os/os_exec_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using os.exec*(). 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | child_pid = os.fork() 9 | if child_pid: 10 | os.waitpid(child_pid, 0) 11 | else: 12 | os.execlp('pwd', 'pwd', '-P') 13 | -------------------------------------------------------------------------------- /os/os_fork_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Simple example of using os.fork to create a new child process. 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | pid = os.fork() 9 | 10 | if pid: 11 | print('Child process id:', pid) 12 | else: 13 | print('I am the child') 14 | -------------------------------------------------------------------------------- /os/os_listdir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """A simple directory listing. 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | import sys 8 | 9 | print(sorted(os.listdir(sys.argv[1]))) 10 | -------------------------------------------------------------------------------- /os/os_process_id_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Find information about the current process. 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | print('This process id:', os.getpid()) 9 | print('Parent process :', os.getppid()) 10 | print('Process group :', os.getpgid(os.getpid())) 11 | print('Parent group :', os.getpgid(os.getppid())) 12 | print('Session id :', os.getsid(0)) 13 | -------------------------------------------------------------------------------- /os/os_spawn_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using spawn*() instead of fork() and exec*(). 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | os.spawnlp(os.P_WAIT, 'pwd', 'pwd', '-P') 9 | -------------------------------------------------------------------------------- /os/os_stat_chmod_example.txt: -------------------------------------------------------------------------------- 1 | contents -------------------------------------------------------------------------------- /os/os_strerror.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Show some of the system error messages 3 | """ 4 | 5 | #end_pymotw_header 6 | import errno 7 | import os 8 | 9 | for num in [errno.ENOENT, errno.EINTR, errno.EBUSY]: 10 | name = errno.errorcode[num] 11 | print('[{num:>2}] {name:<6}: {msg}'.format( 12 | name=name, num=num, msg=os.strerror(num))) 13 | -------------------------------------------------------------------------------- /os/os_system_background.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Running a command in the background 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | import time 8 | 9 | print('Calling...') 10 | os.system('date; (sleep 3; date) &') 11 | 12 | print('Sleeping...') 13 | time.sleep(5) 14 | -------------------------------------------------------------------------------- /os/os_system_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using os.system() to run external commands. 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | # Simple command 9 | os.system('pwd') 10 | -------------------------------------------------------------------------------- /os/os_system_shell.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Using os.system() to run external commands. 3 | """ 4 | 5 | #end_pymotw_header 6 | import os 7 | 8 | # Command with shell expansion 9 | os.system('echo $TMPDIR') 10 | -------------------------------------------------------------------------------- /pathlib/example.txt: -------------------------------------------------------------------------------- 1 | This is the content -------------------------------------------------------------------------------- /pathlib/pathlib_chmod_example.txt: -------------------------------------------------------------------------------- 1 | contents -------------------------------------------------------------------------------- /pathlib/pathlib_convenience.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Convenience methods for Path 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | home = pathlib.Path.home() 14 | print('home: ', home) 15 | 16 | cwd = pathlib.Path.cwd() 17 | print('cwd : ', cwd) 18 | -------------------------------------------------------------------------------- /pathlib/pathlib_glob.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """pathlib glob 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.Path('..') 14 | 15 | for f in p.glob('*.rst'): 16 | print(f) 17 | -------------------------------------------------------------------------------- /pathlib/pathlib_iterdir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """pathlib iterdir 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.Path('.') 14 | 15 | for f in p.iterdir(): 16 | print(f) 17 | -------------------------------------------------------------------------------- /pathlib/pathlib_joinpath.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Building paths with joinpath 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | root = pathlib.PurePosixPath('/') 14 | subdirs = ['usr', 'local'] 15 | usr_local = root.joinpath(*subdirs) 16 | print(usr_local) 17 | -------------------------------------------------------------------------------- /pathlib/pathlib_mkdir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Creating a directory 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.Path('example_dir') 14 | 15 | print('Creating {}'.format(p)) 16 | p.mkdir() 17 | -------------------------------------------------------------------------------- /pathlib/pathlib_ownership.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Show stat info for a file. 3 | """ 4 | 5 | #end_pymotw_header 6 | import pathlib 7 | 8 | p = pathlib.Path(__file__) 9 | 10 | print('{} is owned by {}/{}'.format(p, p.owner(), p.group())) 11 | -------------------------------------------------------------------------------- /pathlib/pathlib_parents.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Parsing paths 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.PurePosixPath('/usr/local/lib') 14 | 15 | print('parent: {}'.format(p.parent)) 16 | 17 | print('\nhierarchy:') 18 | for up in p.parents: 19 | print(up) 20 | -------------------------------------------------------------------------------- /pathlib/pathlib_parts.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Parsing paths 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.PurePosixPath('/usr/local') 14 | print(p.parts) 15 | -------------------------------------------------------------------------------- /pathlib/pathlib_resolve.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Resolving relative paths 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | usr_local = pathlib.Path('/usr/local') 14 | share = usr_local / '..' / 'share' 15 | print(share.resolve()) 16 | -------------------------------------------------------------------------------- /pathlib/pathlib_rglob.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """pathlib rglob 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.Path('..') 14 | 15 | for f in p.rglob('pathlib_*.py'): 16 | print(f) 17 | -------------------------------------------------------------------------------- /pathlib/pathlib_rmdir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Creating a directory 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.Path('example_dir') 14 | 15 | print('Removing {}'.format(p)) 16 | p.rmdir() 17 | -------------------------------------------------------------------------------- /pathlib/pathlib_symlink_to.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Creating symbolic links 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.Path('example_link') 14 | 15 | p.symlink_to('index.rst') 16 | 17 | print(p) 18 | print(p.resolve().name) 19 | -------------------------------------------------------------------------------- /pathlib/pathlib_unlink.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Removing files 8 | """ 9 | 10 | #end_pymotw_header 11 | import pathlib 12 | 13 | p = pathlib.Path('touched') 14 | 15 | p.touch() 16 | 17 | print('exists before removing:', p.exists()) 18 | 19 | p.unlink() 20 | 21 | print('exists after removing:', p.exists()) 22 | -------------------------------------------------------------------------------- /pdb/lorem.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetuer adipiscing elit. 2 | Donec egestas, enim et consectetuer ullamcorper, lectus 3 | ligula rutrum leo, a elementum elit tortor eu quam. 4 | -------------------------------------------------------------------------------- /pdb/pdb_break_remote.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | from pdb_break import f 5 | 6 | f(5) 7 | -------------------------------------------------------------------------------- /pdb/pdb_function_arguments.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | import pdb 8 | 9 | 10 | def recursive_function(n=5, output='to be printed'): 11 | if n > 0: 12 | recursive_function(n - 1) 13 | else: 14 | pdb.set_trace() 15 | print(output) 16 | return 17 | 18 | if __name__ == '__main__': 19 | recursive_function() 20 | -------------------------------------------------------------------------------- /pdb/pdb_interact.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | import pdb 8 | 9 | 10 | def f(): 11 | l = ['a', 'b'] 12 | m = 9 13 | n = 5 14 | print(l, m, n) 15 | 16 | if __name__ == '__main__': 17 | f() 18 | -------------------------------------------------------------------------------- /pdb/pdb_jump.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | 8 | def f(n): 9 | result = [] 10 | j = 0 11 | for i in range(n): 12 | j = i * n + j 13 | j += n 14 | result.append(j) 15 | return result 16 | 17 | if __name__ == '__main__': 18 | print(f(5)) 19 | -------------------------------------------------------------------------------- /pdb/pdb_next.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | import pdb 8 | 9 | 10 | def calc(i, n): 11 | j = i * n 12 | return j 13 | 14 | 15 | def f(n): 16 | for i in range(n): 17 | j = calc(i, n) 18 | print(i, j) 19 | return 20 | 21 | if __name__ == '__main__': 22 | pdb.set_trace() 23 | f(5) 24 | -------------------------------------------------------------------------------- /pdb/pdb_post_mortem.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | 8 | class MyObj: 9 | 10 | def __init__(self, num_loops): 11 | self.count = num_loops 12 | 13 | def go(self): 14 | for i in range(self.num_loops): 15 | print(i) 16 | return 17 | -------------------------------------------------------------------------------- /pdb/pdb_pp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | import pdb 8 | 9 | with open('lorem.txt', 'rt') as f: 10 | lines = f.readlines() 11 | 12 | pdb.set_trace() 13 | -------------------------------------------------------------------------------- /pdb/pdb_run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | import sys 8 | 9 | 10 | def f(): 11 | print('Command-line args:', sys.argv) 12 | return 13 | 14 | if __name__ == '__main__': 15 | f() 16 | -------------------------------------------------------------------------------- /pdb/pdb_script.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | 8 | class MyObj: 9 | 10 | def __init__(self, num_loops): 11 | self.count = num_loops 12 | 13 | def go(self): 14 | for i in range(self.count): 15 | print(i) 16 | return 17 | 18 | if __name__ == '__main__': 19 | MyObj(5).go() 20 | -------------------------------------------------------------------------------- /pdb/pdb_step.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | 7 | import pdb 8 | 9 | 10 | def f(n): 11 | for i in range(n): 12 | j = i * n 13 | print(i, j) 14 | return 15 | 16 | if __name__ == '__main__': 17 | pdb.set_trace() 18 | f(5) 19 | -------------------------------------------------------------------------------- /pickle/pickle_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Pickle an object to a string. 3 | """ 4 | 5 | #end_pymotw_header 6 | import pickle 7 | import pprint 8 | 9 | data = [{'a': 'A', 'b': 2, 'c': 3.0}] 10 | print('DATA:', end=' ') 11 | pprint.pprint(data) 12 | 13 | data_string = pickle.dumps(data) 14 | print('PICKLE: {!r}'.format(data_string)) 15 | -------------------------------------------------------------------------------- /pkgutil/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/pkgutil/__init__.py -------------------------------------------------------------------------------- /pkgutil/demopkg1/shared.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/demopkg2/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import pkgutil 11 | 12 | __path__ = pkgutil.extend_path(__path__, __name__) 13 | __path__.reverse() 14 | -------------------------------------------------------------------------------- /pkgutil/demopkg2/overloaded.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | 11 | def func(): 12 | print('This is the installed version of func().') 13 | -------------------------------------------------------------------------------- /pkgutil/develop/demopkg2/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/develop/demopkg2/overloaded.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | 11 | def func(): 12 | print('This is the development version of func().') 13 | -------------------------------------------------------------------------------- /pkgutil/develop/nested/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/develop/nested/second/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/develop/nested/second/deep.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | def func(): 11 | print('This func() comes from the development ' 12 | 'version of nested.second.deep') 13 | -------------------------------------------------------------------------------- /pkgutil/develop/nested/shallow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | def func(): 11 | print('This func() comes from the development ' 12 | 'version of nested.shallow') 13 | -------------------------------------------------------------------------------- /pkgutil/extension/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/pkgutil/extension/__init__.py -------------------------------------------------------------------------------- /pkgutil/extension/demopkg1/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/extension/demopkg1/not_shared.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/nested/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import pkgutil 11 | 12 | __path__ = pkgutil.extend_path(__path__, __name__) 13 | __path__.reverse() 14 | -------------------------------------------------------------------------------- /pkgutil/nested/second/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/nested/second/deep.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | def func(): 11 | print('This func() comes from the installed ' 12 | 'version of nested.second.deep') 13 | -------------------------------------------------------------------------------- /pkgutil/nested/shallow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | def func(): 11 | print('This func() comes from the installed ' 12 | 'version of nested.shallow') 13 | -------------------------------------------------------------------------------- /pkgutil/os_one/demopkg1/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/os_one/demopkg1/not_shared.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/os_two/demopkg1/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/os_two/demopkg1/not_shared.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | -------------------------------------------------------------------------------- /pkgutil/pkgutil_devel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import demopkg2 11 | print('demopkg2 :', demopkg2.__file__) 12 | 13 | import demopkg2.overloaded 14 | print('demopkg2.overloaded:', demopkg2.overloaded.__file__) 15 | 16 | print() 17 | demopkg2.overloaded.func() 18 | -------------------------------------------------------------------------------- /pkgutil/pkgutil_get_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Load package data 7 | """ 8 | 9 | #end_pymotw_header 10 | import pkgutil 11 | 12 | template = pkgutil.get_data('pkgwithdata', 'templates/base.html') 13 | print(template.decode('utf-8')) 14 | -------------------------------------------------------------------------------- /pkgutil/pkgutil_nested.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import nested 11 | 12 | import nested.shallow 13 | print('nested.shallow:', nested.shallow.__file__) 14 | nested.shallow.func() 15 | 16 | print() 17 | import nested.second.deep 18 | print('nested.second.deep:', nested.second.deep.__file__) 19 | nested.second.deep.func() 20 | -------------------------------------------------------------------------------- /pkgutil/pkgutil_os_specific.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import demopkg1 11 | print('demopkg1:', demopkg1.__file__) 12 | 13 | import demopkg1.shared 14 | print('demopkg1.shared:', demopkg1.shared.__file__) 15 | 16 | import demopkg1.not_shared 17 | print('demopkg1.not_shared:', demopkg1.not_shared.__file__) 18 | -------------------------------------------------------------------------------- /pkgutil/pkgwithdata/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/pkgutil/pkgwithdata/__init__.py -------------------------------------------------------------------------------- /platform/platform_architecture.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import platform 12 | 13 | print('interpreter:', platform.architecture()) 14 | print('/bin/ls :', platform.architecture('/bin/ls')) 15 | -------------------------------------------------------------------------------- /platform/platform_platform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import platform 12 | 13 | print('Normal :', platform.platform()) 14 | print('Aliased:', platform.platform(aliased=True)) 15 | print('Terse :', platform.platform(terse=True)) 16 | -------------------------------------------------------------------------------- /platform/platform_python.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import platform 12 | 13 | print('Version :', platform.python_version()) 14 | print('Version tuple:', platform.python_version_tuple()) 15 | print('Compiler :', platform.python_compiler()) 16 | print('Build :', platform.python_build()) 17 | -------------------------------------------------------------------------------- /pprint/pprint_compact.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Pretty print with pprint 6 | """ 7 | 8 | #end_pymotw_header 9 | from pprint import pprint 10 | 11 | from pprint_data import data 12 | 13 | print('DEFAULT:') 14 | pprint(data, compact=False) 15 | print('\nCOMPACT:') 16 | pprint(data, compact=True) 17 | -------------------------------------------------------------------------------- /pprint/pprint_depth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Pretty print with pprint 6 | """ 7 | 8 | #end_pymotw_header 9 | from pprint import pprint 10 | 11 | from pprint_data import data 12 | 13 | pprint(data, depth=1) 14 | pprint(data, depth=2) 15 | -------------------------------------------------------------------------------- /pprint/pprint_pprint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Pretty print with pprint 6 | """ 7 | 8 | #end_pymotw_header 9 | from pprint import pprint 10 | 11 | from pprint_data import data 12 | 13 | print('PRINT:') 14 | print(data) 15 | print() 16 | print('PPRINT:') 17 | pprint(data) 18 | -------------------------------------------------------------------------------- /pprint/pprint_recursion.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Handling recursive data structures. 6 | """ 7 | 8 | #end_pymotw_header 9 | from pprint import pprint 10 | 11 | local_data = ['a', 'b', 1, 2] 12 | local_data.append(local_data) 13 | 14 | print('id(local_data) =>', id(local_data)) 15 | pprint(local_data) 16 | -------------------------------------------------------------------------------- /pprint/pprint_width.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Pretty print with pprint 6 | """ 7 | 8 | #end_pymotw_header 9 | from pprint import pprint 10 | 11 | from pprint_data import data 12 | 13 | for width in [80, 5]: 14 | print('WIDTH =', width) 15 | pprint(data, width=width) 16 | print() 17 | -------------------------------------------------------------------------------- /profile/profile_runctx.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import profile 11 | from profile_fibonacci_memoized import fib, fib_seq 12 | 13 | if __name__ == '__main__': 14 | profile.runctx( 15 | 'print(fib_seq(n)); print()', 16 | globals(), 17 | {'n': 20}, 18 | ) 19 | -------------------------------------------------------------------------------- /pwd/pwd_getpwuid_process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import pwd 11 | import os 12 | 13 | uid = os.getuid() 14 | user_info = pwd.getpwuid(uid) 15 | print('Currently running with UID={} username={}'.format( 16 | uid, user_info.pw_name)) 17 | -------------------------------------------------------------------------------- /queue/queue_fifo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """FIFO Queue 7 | """ 8 | 9 | #end_pymotw_header 10 | import queue 11 | 12 | q = queue.Queue() 13 | 14 | for i in range(5): 15 | q.put(i) 16 | 17 | while not q.empty(): 18 | print(q.get(), end=' ') 19 | print() 20 | -------------------------------------------------------------------------------- /queue/queue_lifo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """LIFO Queue 7 | """ 8 | 9 | #end_pymotw_header 10 | import queue 11 | 12 | q = queue.LifoQueue() 13 | 14 | for i in range(5): 15 | q.put(i) 16 | 17 | while not q.empty(): 18 | print(q.get(), end=' ') 19 | print() 20 | -------------------------------------------------------------------------------- /random/random_random.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Generate random numbers 7 | """ 8 | 9 | #end_pymotw_header 10 | import random 11 | 12 | for i in range(5): 13 | print('%04.3f' % random.random(), end=' ') 14 | print() 15 | -------------------------------------------------------------------------------- /random/random_randrange.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Random values from a range 7 | """ 8 | 9 | #end_pymotw_header 10 | import random 11 | 12 | for i in range(3): 13 | print(random.randrange(0, 101, 5), end=' ') 14 | print() 15 | -------------------------------------------------------------------------------- /random/random_sample.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Sampling from sequences 7 | """ 8 | 9 | #end_pymotw_header 10 | import random 11 | 12 | with open('/usr/share/dict/words', 'rt') as f: 13 | words = f.readlines() 14 | words = [w.rstrip() for w in words] 15 | 16 | for w in random.sample(words, 5): 17 | print(w) 18 | -------------------------------------------------------------------------------- /random/random_seed.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Generate random numbers 7 | """ 8 | 9 | #end_pymotw_header 10 | import random 11 | 12 | random.seed(1) 13 | 14 | for i in range(5): 15 | print('{:04.3f}'.format(random.random()), end=' ') 16 | print() 17 | -------------------------------------------------------------------------------- /random/random_uniform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Generate random numbers 7 | """ 8 | 9 | #end_pymotw_header 10 | import random 11 | 12 | for i in range(5): 13 | print('{:04.3f}'.format(random.uniform(1, 100)), end=' ') 14 | print() 15 | -------------------------------------------------------------------------------- /re/re_charset_exclude.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Repetition of patterns 7 | """ 8 | 9 | #end_pymotw_header 10 | from re_test_patterns import test_patterns 11 | 12 | test_patterns( 13 | 'This is some text -- with punctuation.', 14 | [('[^-. ]+', 'sequences without -, ., or space')], 15 | ) 16 | -------------------------------------------------------------------------------- /re/re_escape_escapes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Escaping escape codes 7 | """ 8 | 9 | #end_pymotw_header 10 | from re_test_patterns import test_patterns 11 | 12 | test_patterns( 13 | r'\d+ \D+ \s+', 14 | [(r'\\.\+', 'escape code')], 15 | ) 16 | -------------------------------------------------------------------------------- /re/re_findall.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Repetition of patterns 7 | """ 8 | 9 | #end_pymotw_header 10 | import re 11 | 12 | text = 'abbaaabbbbaaaaa' 13 | 14 | pattern = 'ab' 15 | 16 | for match in re.findall(pattern, text): 17 | print('Found {!r}'.format(match)) 18 | -------------------------------------------------------------------------------- /re/re_finditer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Repetition of patterns 7 | """ 8 | 9 | #end_pymotw_header 10 | import re 11 | 12 | text = 'abbaaabbbbaaaaa' 13 | 14 | pattern = 'ab' 15 | 16 | for match in re.finditer(pattern, text): 17 | s = match.start() 18 | e = match.end() 19 | print('Found {!r} at {:d}:{:d}'.format( 20 | text[s:e], s, e)) 21 | -------------------------------------------------------------------------------- /re/re_groups_alternative.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Matching alternative groups 7 | """ 8 | 9 | #end_pymotw_header 10 | from re_test_patterns_groups import test_patterns 11 | 12 | test_patterns( 13 | 'abbaabbba', 14 | [(r'a((a+)|(b+))', 'a then seq. of a or seq. of b'), 15 | (r'a((a|b)+)', 'a then seq. of [ab]')], 16 | ) 17 | -------------------------------------------------------------------------------- /re/re_groups_nested.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Nested groups 7 | """ 8 | 9 | #end_pymotw_header 10 | from re_test_patterns_groups import test_patterns 11 | 12 | test_patterns( 13 | 'abbaabbba', 14 | [(r'a((a*)(b*))', 'a followed by 0-n a and 0-n b')], 15 | ) 16 | -------------------------------------------------------------------------------- /re/re_groups_noncapturing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Noncapturing groups 7 | """ 8 | 9 | #end_pymotw_header 10 | from re_test_patterns_groups import test_patterns 11 | 12 | test_patterns( 13 | 'abbaabbba', 14 | [(r'a((a+)|(b+))', 'capturing form'), 15 | (r'a((?:a+)|(?:b+))', 'noncapturing')], 16 | ) 17 | -------------------------------------------------------------------------------- /re/re_sub.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Substitute based on patterns. 7 | """ 8 | 9 | #end_pymotw_header 10 | import re 11 | 12 | bold = re.compile(r'\*{2}(.*?)\*{2}') 13 | 14 | text = 'Make this **bold**. This **too**.' 15 | 16 | print('Text:', text) 17 | print('Bold:', bold.sub(r'\1', text)) 18 | -------------------------------------------------------------------------------- /re/re_sub_count.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Substitute based on patterns. 7 | """ 8 | 9 | #end_pymotw_header 10 | import re 11 | 12 | bold = re.compile(r'\*{2}(.*?)\*{2}') 13 | 14 | text = 'Make this **bold**. This **too**.' 15 | 16 | print('Text:', text) 17 | print('Bold:', bold.sub(r'\1', text, count=1)) 18 | -------------------------------------------------------------------------------- /re/re_sub_named_groups.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Substitute based on patterns. 7 | """ 8 | 9 | #end_pymotw_header 10 | import re 11 | 12 | bold = re.compile(r'\*{2}(?P.*?)\*{2}') 13 | 14 | text = 'Make this **bold**. This **too**.' 15 | 16 | print('Text:', text) 17 | print('Bold:', bold.sub(r'\g', text)) 18 | -------------------------------------------------------------------------------- /re/re_subn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Substitute based on patterns. 7 | """ 8 | 9 | #end_pymotw_header 10 | import re 11 | 12 | bold = re.compile(r'\*{2}(.*?)\*{2}') 13 | 14 | text = 'Make this **bold**. This **too**.' 15 | 16 | print('Text:', text) 17 | print('Bold:', bold.subn(r'\1', text)) 18 | -------------------------------------------------------------------------------- /shelve/shelve_create.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Creating a new shelf. 3 | """ 4 | 5 | #end_pymotw_header 6 | import shelve 7 | 8 | with shelve.open('test_shelf.db') as s: 9 | s['key1'] = { 10 | 'int': 10, 11 | 'float': 9.5, 12 | 'string': 'Sample data', 13 | } 14 | -------------------------------------------------------------------------------- /shelve/shelve_existing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Opening an existing shelf. 3 | """ 4 | 5 | #end_pymotw_header 6 | import shelve 7 | 8 | with shelve.open('test_shelf.db') as s: 9 | existing = s['key1'] 10 | 11 | print(existing) 12 | -------------------------------------------------------------------------------- /shelve/shelve_readonly.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Opening an existing shelf read-only. 3 | """ 4 | 5 | #end_pymotw_header 6 | import dbm 7 | import shelve 8 | 9 | with shelve.open('test_shelf.db', flag='r') as s: 10 | print('Existing:', s['key1']) 11 | try: 12 | s['key1'] = 'new value' 13 | except dbm.error as err: 14 | print('ERROR: {}'.format(err)) 15 | -------------------------------------------------------------------------------- /shelve/shelve_withoutwriteback.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Modifying an existing shelf opened with write-back enabled. 3 | """ 4 | 5 | #end_pymotw_header 6 | import shelve 7 | 8 | with shelve.open('test_shelf.db') as s: 9 | print(s['key1']) 10 | s['key1']['new_value'] = 'this was not here before' 11 | 12 | with shelve.open('test_shelf.db', writeback=True) as s: 13 | print(s['key1']) 14 | -------------------------------------------------------------------------------- /shlex/apostrophe.txt: -------------------------------------------------------------------------------- 1 | This string has an embedded apostrophe, doesn't it? -------------------------------------------------------------------------------- /shlex/comments.txt: -------------------------------------------------------------------------------- 1 | This line is recognized. 2 | # But this line is ignored. 3 | And this line is processed. -------------------------------------------------------------------------------- /shlex/quotes.txt: -------------------------------------------------------------------------------- 1 | This string has embedded "double quotes" and 2 | 'single quotes' in it, and even "a 'nested example'". 3 | -------------------------------------------------------------------------------- /shlex/shlex_split.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | """Splitting strings with shlex. 5 | """ 6 | 7 | #end_pymotw_header 8 | import shlex 9 | 10 | text = """This text has "quoted parts" inside it.""" 11 | print('ORIGINAL: {!r}'.format(text)) 12 | print() 13 | 14 | print('TOKENS:') 15 | print(shlex.split(text)) 16 | -------------------------------------------------------------------------------- /shlex/shlex_table.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | """Other uses for the parser. 5 | """ 6 | 7 | #end_pymotw_header 8 | import shlex 9 | 10 | text = """|Col 1||Col 2||Col 3|""" 11 | print('ORIGINAL: {!r}'.format(text)) 12 | print() 13 | 14 | lexer = shlex.shlex(text) 15 | lexer.quotes = '|' 16 | 17 | print('TOKENS:') 18 | for token in lexer: 19 | print('{!r}'.format(token)) 20 | -------------------------------------------------------------------------------- /shutil/config.ini: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/shutil/config.ini -------------------------------------------------------------------------------- /shutil/file_to_change.txt: -------------------------------------------------------------------------------- 1 | content -------------------------------------------------------------------------------- /shutil/shutil_copy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Copying a file 3 | """ 4 | 5 | #end_pymotw_header 6 | import glob 7 | import os 8 | import shutil 9 | 10 | os.mkdir('example') 11 | print('BEFORE:', glob.glob('example/*')) 12 | 13 | shutil.copy('shutil_copy.py', 'example') 14 | 15 | print('AFTER :', glob.glob('example/*')) 16 | -------------------------------------------------------------------------------- /shutil/shutil_copyfile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Copying a file 3 | """ 4 | 5 | #end_pymotw_header 6 | import glob 7 | import shutil 8 | 9 | print('BEFORE:', glob.glob('shutil_copyfile.*')) 10 | 11 | shutil.copyfile('shutil_copyfile.py', 'shutil_copyfile.py.copy') 12 | 13 | print('AFTER:', glob.glob('shutil_copyfile.*')) 14 | -------------------------------------------------------------------------------- /shutil/shutil_copytree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Copying an entire tree of files. 3 | """ 4 | 5 | #end_pymotw_header 6 | import glob 7 | import pprint 8 | import shutil 9 | 10 | print('BEFORE:') 11 | pprint.pprint(glob.glob('/tmp/example/*')) 12 | 13 | shutil.copytree('../shutil', '/tmp/example') 14 | 15 | print('\nAFTER:') 16 | pprint.pprint(glob.glob('/tmp/example/*')) 17 | -------------------------------------------------------------------------------- /shutil/shutil_get_archive_formats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Which archive formats are supported? 8 | """ 9 | 10 | #end_pymotw_header 11 | import shutil 12 | 13 | for format, description in shutil.get_archive_formats(): 14 | print('{:<5}: {}'.format(format, description)) 15 | -------------------------------------------------------------------------------- /shutil/shutil_get_unpack_formats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Which archive formats can be extracted? 8 | """ 9 | 10 | #end_pymotw_header 11 | import shutil 12 | 13 | for format, exts, description in shutil.get_unpack_formats(): 14 | print('{:<5}: {}, names ending in {}'.format( 15 | format, description, exts)) 16 | -------------------------------------------------------------------------------- /shutil/shutil_move.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Copying a file 3 | """ 4 | 5 | #end_pymotw_header 6 | import glob 7 | import shutil 8 | 9 | with open('example.txt', 'wt') as f: 10 | f.write('contents') 11 | 12 | print('BEFORE: ', glob.glob('example*')) 13 | 14 | shutil.move('example.txt', 'example.out') 15 | 16 | print('AFTER : ', glob.glob('example*')) 17 | -------------------------------------------------------------------------------- /shutil/shutil_rmtree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Remove an entire tree of files. 3 | """ 4 | 5 | #end_pymotw_header 6 | import glob 7 | import pprint 8 | import shutil 9 | 10 | print('BEFORE:') 11 | pprint.pprint(glob.glob('/tmp/example/*')) 12 | 13 | shutil.rmtree('/tmp/example') 14 | 15 | print('\nAFTER:') 16 | pprint.pprint(glob.glob('/tmp/example/*')) 17 | -------------------------------------------------------------------------------- /shutil/shutil_which.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2016 Doug Hellmann. All rights reserved. 5 | # Written for https://pymotw.com 6 | # 7 | """Find a program on $PATH 8 | """ 9 | 10 | #end_pymotw_header 11 | import shutil 12 | 13 | print(shutil.which('virtualenv')) 14 | print(shutil.which('tox')) 15 | print(shutil.which('no-such-program')) 16 | -------------------------------------------------------------------------------- /site/multiple_pth/a.pth: -------------------------------------------------------------------------------- 1 | ./from_a 2 | -------------------------------------------------------------------------------- /site/multiple_pth/b.pth: -------------------------------------------------------------------------------- 1 | ./from_b 2 | -------------------------------------------------------------------------------- /site/multiple_pth/from_a/mymodule.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Empty module for example. 7 | """ 8 | 9 | #end_pymotw_header 10 | import os 11 | print('Loaded {} from {}'.format( 12 | __name__, __file__[len(os.getcwd()) + 1:]) 13 | ) 14 | -------------------------------------------------------------------------------- /site/multiple_pth/from_b/mymodule.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Empty module for example. 7 | """ 8 | 9 | #end_pymotw_header 10 | import os 11 | print('Loaded {} from {}'.format( 12 | __name__, __file__[len(os.getcwd()) + 1:]) 13 | ) 14 | -------------------------------------------------------------------------------- /site/site_user_base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Show the user base directory. 7 | """ 8 | 9 | #end_pymotw_header 10 | import site 11 | 12 | print('Base:', site.USER_BASE) 13 | print('Site:', site.USER_SITE) 14 | -------------------------------------------------------------------------------- /site/with_modules/mymodule.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Empty module for example. 7 | """ 8 | 9 | #end_pymotw_header 10 | import os 11 | print('Loaded {} from {}'.format( 12 | __name__, __file__[len(os.getcwd()) + 1:]) 13 | ) 14 | -------------------------------------------------------------------------------- /site/with_pth/pymotw.pth: -------------------------------------------------------------------------------- 1 | # Add a single subdirectory to the path. 2 | ./subdir 3 | -------------------------------------------------------------------------------- /site/with_pth/subdir/mymodule.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Empty module for example. 7 | """ 8 | 9 | #end_pymotw_header 10 | import os 11 | print('Loaded {} from {}'.format( 12 | __name__, __file__[len(os.getcwd()) + 1:]) 13 | ) 14 | -------------------------------------------------------------------------------- /site/with_sitecustomize/site_sitecustomize.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Run in with_sitecustomize directory. 7 | """ 8 | 9 | #end_pymotw_header 10 | import sys 11 | 12 | print('Running main program from\n{}'.format(sys.argv[0])) 13 | 14 | print('End of path:', sys.path[-1]) 15 | -------------------------------------------------------------------------------- /site/with_usercustomize/site_usercustomize.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Run in with_usercustomize directory. 7 | """ 8 | 9 | #end_pymotw_header 10 | import sys 11 | 12 | print('Running main program from\n{}'.format(sys.argv[0])) 13 | 14 | print('End of path:', sys.path[-1]) 15 | -------------------------------------------------------------------------------- /smtpd/smtpd_debug.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import smtpd 12 | import asyncore 13 | 14 | server = smtpd.DebuggingServer(('127.0.0.1', 1025), None) 15 | 16 | asyncore.loop() 17 | -------------------------------------------------------------------------------- /smtpd/smtpd_proxy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import smtpd 12 | import asyncore 13 | 14 | server = smtpd.PureProxy(('127.0.0.1', 1025), ('mail', 25)) 15 | 16 | asyncore.loop() 17 | -------------------------------------------------------------------------------- /socket/socket_getfqdn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Look up the fully qualified domain name for a host. 7 | """ 8 | 9 | #end_pymotw_header 10 | import socket 11 | 12 | for host in ['apu', 'pymotw.com']: 13 | print('{:>10} : {}'.format(host, socket.getfqdn(host))) 14 | -------------------------------------------------------------------------------- /socket/socket_gethostbyaddr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Look up a hostname from its address. 7 | """ 8 | 9 | #end_pymotw_header 10 | import socket 11 | 12 | hostname, aliases, addresses = socket.gethostbyaddr('10.9.0.10') 13 | 14 | print('Hostname :', hostname) 15 | print('Aliases :', aliases) 16 | print('Addresses:', addresses) 17 | -------------------------------------------------------------------------------- /socket/socket_gethostname.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Look up the name of the current host 7 | """ 8 | 9 | #end_pymotw_header 10 | import socket 11 | 12 | print(socket.gethostname()) 13 | -------------------------------------------------------------------------------- /socket/socket_getservbyport.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Look up a service name by its port number. 7 | """ 8 | 9 | #end_pymotw_header 10 | import socket 11 | from urllib.parse import urlunparse 12 | 13 | for port in [80, 443, 21, 70, 25, 143, 993, 110, 995]: 14 | url = '{}://example.com/'.format(socket.getservbyport(port)) 15 | print(url) 16 | -------------------------------------------------------------------------------- /statistics/statistics_mean.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | """Arithmetic mean 5 | """ 6 | 7 | #end_pymotw_header 8 | from statistics import * 9 | 10 | data = [1, 2, 2, 5, 10, 12] 11 | 12 | print('{:0.2f}'.format(mean(data))) 13 | -------------------------------------------------------------------------------- /statistics/statistics_median.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | """ 5 | """ 6 | 7 | #end_pymotw_header 8 | from statistics import * 9 | 10 | data = [1, 2, 2, 5, 10, 12] 11 | 12 | print('median : {:0.2f}'.format(median(data))) 13 | print('low : {:0.2f}'.format(median_low(data))) 14 | print('high : {:0.2f}'.format(median_high(data))) 15 | -------------------------------------------------------------------------------- /statistics/statistics_median_grouped.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | """ 5 | """ 6 | 7 | #end_pymotw_header 8 | from statistics import * 9 | 10 | data = [10, 20, 30, 40] 11 | 12 | print('1: {:0.2f}'.format(median_grouped(data, interval=1))) 13 | print('2: {:0.2f}'.format(median_grouped(data, interval=2))) 14 | print('3: {:0.2f}'.format(median_grouped(data, interval=3))) 15 | -------------------------------------------------------------------------------- /statistics/statistics_mode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | """ 5 | """ 6 | 7 | #end_pymotw_header 8 | from statistics import * 9 | 10 | data = [1, 2, 2, 5, 10, 12] 11 | 12 | print(mode(data)) 13 | -------------------------------------------------------------------------------- /string/string_capwords.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import string 11 | 12 | s = 'The quick brown fox jumped over the lazy dog.' 13 | 14 | print(s) 15 | print(string.capwords(s)) 16 | -------------------------------------------------------------------------------- /string/string_template_defaultpattern.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import string 11 | 12 | t = string.Template('$var') 13 | print(t.pattern.pattern) 14 | -------------------------------------------------------------------------------- /struct/struct_unpack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import struct 12 | import binascii 13 | 14 | packed_data = binascii.unhexlify(b'0100000061620000cdcc2c40') 15 | 16 | s = struct.Struct('I 2s f') 17 | unpacked_data = s.unpack(packed_data) 18 | print('Unpacked Values:', unpacked_data) 19 | -------------------------------------------------------------------------------- /subprocess/subprocess_os_system.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Replacing os.system with subprocess. 3 | """ 4 | 5 | #end_pymotw_header 6 | import subprocess 7 | 8 | completed = subprocess.run(['ls', '-1']) 9 | print('returncode:', completed.returncode) 10 | -------------------------------------------------------------------------------- /subprocess/subprocess_popen_read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import subprocess 12 | 13 | print('read:') 14 | proc = subprocess.Popen( 15 | ['echo', '"to stdout"'], 16 | stdout=subprocess.PIPE, 17 | ) 18 | stdout_value = proc.communicate()[0].decode('utf-8') 19 | print('stdout:', repr(stdout_value)) 20 | -------------------------------------------------------------------------------- /subprocess/subprocess_popen_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import subprocess 12 | 13 | print('write:') 14 | proc = subprocess.Popen( 15 | ['cat', '-'], 16 | stdin=subprocess.PIPE, 17 | ) 18 | proc.communicate('stdin: to stdin\n'.encode('utf-8')) 19 | -------------------------------------------------------------------------------- /subprocess/subprocess_run_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2010 Doug Hellmann. 4 | # 5 | """Checking exit codes from external processes 6 | """ 7 | 8 | #end_pymotw_header 9 | import subprocess 10 | 11 | try: 12 | subprocess.run(['false'], check=True) 13 | except subprocess.CalledProcessError as err: 14 | print('ERROR:', err) 15 | -------------------------------------------------------------------------------- /subprocess/subprocess_shell_variables.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import subprocess 11 | 12 | completed = subprocess.run('echo $HOME', shell=True) 13 | print('returncode:', completed.returncode) 14 | -------------------------------------------------------------------------------- /sys/sys_argv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('Arguments:', sys.argv) 7 | -------------------------------------------------------------------------------- /sys/sys_builtins.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | import textwrap 6 | 7 | name_text = ', '.join(sorted(sys.builtin_module_names)) 8 | 9 | print(textwrap.fill(name_text, width=64)) 10 | -------------------------------------------------------------------------------- /sys/sys_byteorder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print(sys.byteorder) 7 | -------------------------------------------------------------------------------- /sys/sys_excepthook.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | 7 | def my_excepthook(type, value, traceback): 8 | print('Unhandled error:', type, value) 9 | 10 | 11 | sys.excepthook = my_excepthook 12 | 13 | print('Before exception') 14 | 15 | raise RuntimeError('This is the error message') 16 | 17 | print('After exception') 18 | -------------------------------------------------------------------------------- /sys/sys_exit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | exit_code = int(sys.argv[1]) 7 | sys.exit(exit_code) 8 | -------------------------------------------------------------------------------- /sys/sys_getrefcount.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | one = [] 7 | print('At start :', sys.getrefcount(one)) 8 | 9 | two = one 10 | 11 | print('Second reference :', sys.getrefcount(one)) 12 | 13 | del two 14 | 15 | print('After del :', sys.getrefcount(one)) 16 | -------------------------------------------------------------------------------- /sys/sys_getsizeof.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | 7 | class MyClass: 8 | pass 9 | 10 | 11 | objects = [ 12 | [], (), {}, 'c', 'string', b'bytes', 1, 2.3, 13 | MyClass, MyClass(), 14 | ] 15 | 16 | for obj in objects: 17 | print('{:>10} : {}'.format(type(obj).__name__, 18 | sys.getsizeof(obj))) 19 | -------------------------------------------------------------------------------- /sys/sys_implementation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | 7 | print('Name:', sys.implementation.name) 8 | print('Version:', sys.implementation.version) 9 | print('Cache tag:', sys.implementation.cache_tag) 10 | -------------------------------------------------------------------------------- /sys/sys_int_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('Number of bits used to hold each digit:', 7 | sys.int_info.bits_per_digit) 8 | print('Size in bytes of C type used to hold each digit:', 9 | sys.int_info.sizeof_digit) 10 | -------------------------------------------------------------------------------- /sys/sys_locations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('Interpreter executable:') 7 | print(sys.executable) 8 | print('\nInstallation prefix:') 9 | print(sys.prefix) 10 | -------------------------------------------------------------------------------- /sys/sys_maximums.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('maxsize :', sys.maxsize) 7 | print('maxunicode:', sys.maxunicode) 8 | -------------------------------------------------------------------------------- /sys/sys_modules.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | import textwrap 6 | 7 | names = sorted(sys.modules.keys()) 8 | name_text = ', '.join(names) 9 | 10 | print(textwrap.fill(name_text, width=64)) 11 | -------------------------------------------------------------------------------- /sys/sys_path_show.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | for d in sys.path: 7 | print(d) 8 | -------------------------------------------------------------------------------- /sys/sys_platform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('This interpreter was built for:', sys.platform) 7 | -------------------------------------------------------------------------------- /sys/sys_ps1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | 7 | class LineCounter: 8 | 9 | def __init__(self): 10 | self.count = 0 11 | 12 | def __str__(self): 13 | self.count += 1 14 | return '({:3d})> '.format(self.count) 15 | -------------------------------------------------------------------------------- /sys/sys_shelve_importer_missing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | import sys_shelve_importer 6 | 7 | filename = '/tmp/pymotw_import_example.shelve' 8 | sys.path_hooks.append(sys_shelve_importer.ShelveFinder) 9 | sys.path.insert(0, filename) 10 | 11 | try: 12 | import package.module3 13 | except ImportError as e: 14 | print('Failed to import:', e) 15 | -------------------------------------------------------------------------------- /sys/sys_stdio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('STATUS: Reading from stdin', file=sys.stderr) 7 | 8 | data = sys.stdin.read() 9 | 10 | print('STATUS: Writing data to stdout', file=sys.stderr) 11 | 12 | sys.stdout.write(data) 13 | sys.stdout.flush() 14 | 15 | print('STATUS: Done', file=sys.stderr) 16 | -------------------------------------------------------------------------------- /sys/sys_unicode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('Default encoding :', sys.getdefaultencoding()) 7 | print('File system encoding :', sys.getfilesystemencoding()) 8 | -------------------------------------------------------------------------------- /sys/sys_version_values.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | #end_pymotw_header 4 | import sys 5 | 6 | print('Version info:') 7 | print() 8 | print('sys.version =', repr(sys.version)) 9 | print('sys.version_info =', sys.version_info) 10 | print('sys.hexversion =', hex(sys.hexversion)) 11 | print('sys.api_version =', sys.api_version) 12 | -------------------------------------------------------------------------------- /sysconfig/sysconfig_get_config_var.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """All configuration variables. 7 | """ 8 | 9 | #end_pymotw_header 10 | import sysconfig 11 | 12 | print('User base directory:', 13 | sysconfig.get_config_var('userbase')) 14 | print('Unknown variable :', 15 | sysconfig.get_config_var('NoSuchVariable')) 16 | -------------------------------------------------------------------------------- /sysconfig/sysconfig_get_config_vars_by_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """All configuration variables. 7 | """ 8 | 9 | #end_pymotw_header 10 | import sysconfig 11 | 12 | bases = sysconfig.get_config_vars('base', 'platbase', 'userbase') 13 | print('Base directories:') 14 | for b in bases: 15 | print(' ', b) 16 | -------------------------------------------------------------------------------- /sysconfig/sysconfig_get_path_names.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """The names of the paths in a scheme. 7 | """ 8 | 9 | #end_pymotw_header 10 | import sysconfig 11 | 12 | for name in sysconfig.get_path_names(): 13 | print(name) 14 | -------------------------------------------------------------------------------- /sysconfig/sysconfig_get_platform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Platform specifier for binary modules 7 | """ 8 | 9 | #end_pymotw_header 10 | import sysconfig 11 | 12 | print(sysconfig.get_platform()) 13 | -------------------------------------------------------------------------------- /sysconfig/sysconfig_get_scheme_names.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Installation schemes. 7 | """ 8 | 9 | #end_pymotw_header 10 | import sysconfig 11 | 12 | for name in sysconfig.get_scheme_names(): 13 | print(name) 14 | -------------------------------------------------------------------------------- /tabnanny/tabnanny_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann. All rights reserved. 5 | # 6 | """Using tabnanny from your own code 7 | """ 8 | 9 | #end_pymotw_header 10 | import sys 11 | import tabnanny 12 | 13 | # Turn on verbose mode 14 | tabnanny.verbose = 1 15 | 16 | for dirname in sys.argv[1:]: 17 | tabnanny.check(dirname) 18 | -------------------------------------------------------------------------------- /tarfile/README.txt: -------------------------------------------------------------------------------- 1 | The examples for the tarfile module use this file and 2 | example.tar as data. 3 | -------------------------------------------------------------------------------- /tarfile/outdir/README.txt: -------------------------------------------------------------------------------- 1 | The examples for the tarfile module use this file and 2 | example.tar as data. 3 | -------------------------------------------------------------------------------- /tarfile/tarfile_extract.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import tarfile 12 | import os 13 | 14 | os.mkdir('outdir') 15 | with tarfile.open('example.tar', 'r') as t: 16 | t.extract('README.txt', 'outdir') 17 | print(os.listdir('outdir')) 18 | -------------------------------------------------------------------------------- /tarfile/tarfile_extractall.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import tarfile 12 | import os 13 | 14 | os.mkdir('outdir') 15 | with tarfile.open('example.tar', 'r') as t: 16 | t.extractall('outdir') 17 | print(os.listdir('outdir')) 18 | -------------------------------------------------------------------------------- /tarfile/tarfile_getnames.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2009 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import tarfile 12 | 13 | with tarfile.open('example.tar', 'r') as t: 14 | print(t.getnames()) 15 | -------------------------------------------------------------------------------- /tempfile/tempfile_TemporaryFile_binary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import os 12 | import tempfile 13 | 14 | with tempfile.TemporaryFile() as temp: 15 | temp.write(b'Some data') 16 | 17 | temp.seek(0) 18 | print(temp.read()) 19 | -------------------------------------------------------------------------------- /tempfile/tempfile_TemporaryFile_text.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import tempfile 12 | 13 | with tempfile.TemporaryFile(mode='w+t') as f: 14 | f.writelines(['first\n', 'second\n']) 15 | 16 | f.seek(0) 17 | for line in f: 18 | print(line.rstrip()) 19 | -------------------------------------------------------------------------------- /tempfile/tempfile_settings.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import tempfile 12 | 13 | print('gettempdir():', tempfile.gettempdir()) 14 | print('gettempprefix():', tempfile.gettempprefix()) 15 | -------------------------------------------------------------------------------- /tempfile/tempfile_tempdir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import tempfile 12 | 13 | tempfile.tempdir = '/I/changed/this/path' 14 | print('gettempdir():', tempfile.gettempdir()) 15 | -------------------------------------------------------------------------------- /textwrap/textwrap_dedent.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import textwrap 11 | from textwrap_example import sample_text 12 | 13 | dedented_text = textwrap.dedent(sample_text) 14 | print('Dedented:') 15 | print(dedented_text) 16 | -------------------------------------------------------------------------------- /textwrap/textwrap_fill.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import textwrap 11 | from textwrap_example import sample_text 12 | 13 | print(textwrap.fill(sample_text, width=50)) 14 | -------------------------------------------------------------------------------- /threading/threading_lock_reacquire.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Normal locks cannot be acquired more than once 7 | """ 8 | 9 | #end_pymotw_header 10 | import threading 11 | 12 | lock = threading.Lock() 13 | 14 | print('First try :', lock.acquire()) 15 | print('Second try:', lock.acquire(0)) 16 | -------------------------------------------------------------------------------- /threading/threading_rlock.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Re-entrant locks 7 | """ 8 | 9 | #end_pymotw_header 10 | import threading 11 | 12 | lock = threading.RLock() 13 | 14 | print('First try :', lock.acquire()) 15 | print('Second try:', lock.acquire(0)) 16 | -------------------------------------------------------------------------------- /time/time_ctime.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import time 11 | 12 | print('The time is :', time.ctime()) 13 | later = time.time() + 15 14 | print('15 secs from now :', time.ctime(later)) 15 | -------------------------------------------------------------------------------- /time/time_time.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import time 11 | 12 | print('The time is:', time.time()) 13 | -------------------------------------------------------------------------------- /timeit/timeit_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Example of using timeit programatically. 3 | 4 | Time various ways to populate and check a dictionary 5 | using a long list of strings and integers. 6 | """ 7 | 8 | #end_pymotw_header 9 | import timeit 10 | 11 | # using setitem 12 | t = timeit.Timer("print('main statement')", "print('setup')") 13 | 14 | print('TIMEIT:') 15 | print(t.timeit(2)) 16 | 17 | print('REPEAT:') 18 | print(t.repeat(3, 2)) 19 | -------------------------------------------------------------------------------- /timeit/timeit_setitem.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | """ 4 | 5 | #end_pymotw_header 6 | 7 | def test_setitem(range_size=1000): 8 | l = [(str(x), x) for x in range(range_size)] 9 | d = {} 10 | for s, i in l: 11 | d[s] = i 12 | -------------------------------------------------------------------------------- /trace/trace_CoverageResults.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import trace 12 | from trace_example.recurse import recurse 13 | 14 | tracer = trace.Trace(count=True, trace=False) 15 | tracer.runfunc(recurse, 2) 16 | 17 | results = tracer.results() 18 | results.write_results(coverdir='coverdir2') 19 | -------------------------------------------------------------------------------- /trace/trace_example/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bat67/The-Python-Standard-Library-by-Example/95d2d71d949a276d62520294906415129733aabd/trace/trace_example/__init__.py -------------------------------------------------------------------------------- /trace/trace_example/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | from recurse import recurse 11 | 12 | 13 | def main(): 14 | print('This is the main program.') 15 | recurse(2) 16 | 17 | 18 | if __name__ == '__main__': 19 | main() 20 | -------------------------------------------------------------------------------- /trace/trace_example/recurse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | 11 | def recurse(level): 12 | print('recurse({})'.format(level)) 13 | if level: 14 | recurse(level - 1) 15 | 16 | 17 | def not_called(): 18 | print('This function is never called.') 19 | -------------------------------------------------------------------------------- /trace/trace_run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import trace 12 | from trace_example.recurse import recurse 13 | 14 | tracer = trace.Trace(count=False, trace=True) 15 | tracer.run('recurse(2)') 16 | -------------------------------------------------------------------------------- /trace/trace_runfunc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | 10 | #end_pymotw_header 11 | import trace 12 | from trace_example.recurse import recurse 13 | 14 | tracer = trace.Trace(count=False, trace=True) 15 | tracer.runfunc(recurse, 2) 16 | -------------------------------------------------------------------------------- /traceback/traceback_format_exc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import traceback 11 | import sys 12 | 13 | from traceback_example import produce_exception 14 | 15 | try: 16 | produce_exception() 17 | except Exception as err: 18 | print('format_exc():') 19 | print(traceback.format_exc()) 20 | -------------------------------------------------------------------------------- /unittest/unittest_expectedfailure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | """ 4 | 5 | #end_pymotw_header 6 | import unittest 7 | 8 | 9 | class Test(unittest.TestCase): 10 | 11 | @unittest.expectedFailure 12 | def test_never_passes(self): 13 | self.assertTrue(False) 14 | 15 | @unittest.expectedFailure 16 | def test_always_passes(self): 17 | self.assertTrue(True) 18 | -------------------------------------------------------------------------------- /unittest/unittest_failwithmessage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """A test that fails with a custom message. 3 | """ 4 | 5 | #end_pymotw_header 6 | import unittest 7 | 8 | 9 | class FailureMessageTest(unittest.TestCase): 10 | 11 | def testFail(self): 12 | self.assertFalse(True, 'failure message goes here') 13 | -------------------------------------------------------------------------------- /unittest/unittest_in.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Test for equality 3 | """ 4 | 5 | #end_pymotw_header 6 | import unittest 7 | 8 | 9 | class ContainerMembershipTest(unittest.TestCase): 10 | 11 | def testDict(self): 12 | self.assertIn(4, {1: 'a', 2: 'b', 3: 'c'}) 13 | 14 | def testList(self): 15 | self.assertIn(4, [1, 2, 3]) 16 | 17 | def testSet(self): 18 | self.assertIn(4, set([1, 2, 3])) 19 | -------------------------------------------------------------------------------- /unittest/unittest_outcomes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Demonstrate possible test outcomes 3 | """ 4 | 5 | #end_pymotw_header 6 | import unittest 7 | 8 | 9 | class OutcomesTest(unittest.TestCase): 10 | 11 | def testPass(self): 12 | return 13 | 14 | def testFail(self): 15 | self.assertFalse(True) 16 | 17 | def testError(self): 18 | raise RuntimeError('Test error!') 19 | -------------------------------------------------------------------------------- /unittest/unittest_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Simplistic examples of unit tests. 3 | """ 4 | 5 | #end_pymotw_header 6 | import unittest 7 | 8 | 9 | class SimplisticTest(unittest.TestCase): 10 | 11 | def test(self): 12 | a = 'a' 13 | b = 'a' 14 | self.assertEqual(a, b) 15 | -------------------------------------------------------------------------------- /unittest/unittest_truth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Test for truth 3 | """ 4 | 5 | #end_pymotw_header 6 | import unittest 7 | 8 | 9 | class TruthTest(unittest.TestCase): 10 | 11 | def testAssertTrue(self): 12 | self.assertTrue(True) 13 | 14 | def testAssertFalse(self): 15 | self.assertFalse(False) 16 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_geturl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Parsing URLs 3 | """ 4 | 5 | #end_pymotw_header 6 | from urllib.parse import urlparse 7 | 8 | original = 'http://netloc/path;param?query=arg#frag' 9 | print('ORIG :', original) 10 | parsed = urlparse(original) 11 | print('PARSED:', parsed.geturl()) 12 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_parse_qs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | from urllib.parse import parse_qs, parse_qsl 11 | 12 | encoded = 'foo=foo1&foo=foo2' 13 | 14 | print('parse_qs :', parse_qs(encoded)) 15 | print('parse_qsl:', parse_qsl(encoded)) 16 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_quote.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | from urllib.parse import quote, quote_plus, urlencode 11 | 12 | url = 'http://localhost:8080/~hellmann/' 13 | print('urlencode() :', urlencode({'url': url})) 14 | print('quote() :', quote(url)) 15 | print('quote_plus():', quote_plus(url)) 16 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_unquote.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | from urllib.parse import unquote, unquote_plus 11 | 12 | print(unquote('http%3A//localhost%3A8080/%7Ehellmann/')) 13 | print(unquote_plus( 14 | 'http%3A%2F%2Flocalhost%3A8080%2F%7Ehellmann%2F' 15 | )) 16 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urldefrag.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Remove fragment portion of URL 3 | """ 4 | 5 | #end_pymotw_header 6 | from urllib.parse import urldefrag 7 | 8 | original = 'http://netloc/path;param?query=arg#frag' 9 | print('original:', original) 10 | d = urldefrag(original) 11 | print('url :', d.url) 12 | print('fragment:', d.fragment) 13 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urlencode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | from urllib.parse import urlencode 11 | 12 | query_args = { 13 | 'q': 'query string', 14 | 'foo': 'bar', 15 | } 16 | encoded_args = urlencode(query_args) 17 | print('Encoded:', encoded_args) 18 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urlencode_doseq.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | from urllib.parse import urlencode 11 | 12 | query_args = { 13 | 'foo': ['foo1', 'foo2'], 14 | } 15 | print('Single :', urlencode(query_args)) 16 | print('Sequence:', urlencode(query_args, doseq=True)) 17 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urljoin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Joining relative fragments into absolute URLs 3 | """ 4 | 5 | #end_pymotw_header 6 | from urllib.parse import urljoin 7 | 8 | print(urljoin('http://www.example.com/path/file.html', 9 | 'anotherfile.html')) 10 | print(urljoin('http://www.example.com/path/file.html', 11 | '../anotherfile.html')) 12 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urljoin_with_path.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Joining fragments into absolute URLs 3 | """ 4 | 5 | #end_pymotw_header 6 | from urllib.parse import urljoin 7 | 8 | print(urljoin('http://www.example.com/path/', 9 | '/subpath/file.html')) 10 | print(urljoin('http://www.example.com/path/', 11 | 'subpath/file.html')) 12 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urlparse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Parsing URLs 3 | """ 4 | 5 | #end_pymotw_header 6 | from urllib.parse import urlparse 7 | 8 | url = 'http://netloc/path;param?query=arg#frag' 9 | parsed = urlparse(url) 10 | print(parsed) 11 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urlunparse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Parsing URLs 3 | """ 4 | 5 | #end_pymotw_header 6 | from urllib.parse import urlparse, urlunparse 7 | 8 | original = 'http://netloc/path;param?query=arg#frag' 9 | print('ORIG :', original) 10 | parsed = urlparse(original) 11 | print('PARSED:', type(parsed), parsed) 12 | t = parsed[:] 13 | print('TUPLE :', type(t), t) 14 | print('NEW :', urlunparse(t)) 15 | -------------------------------------------------------------------------------- /urllib.parse/urllib_parse_urlunparseextra.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Parsing URLs 3 | """ 4 | 5 | #end_pymotw_header 6 | from urllib.parse import urlparse, urlunparse 7 | 8 | original = 'http://netloc/path;?#' 9 | print('ORIG :', original) 10 | parsed = urlparse(original) 11 | print('PARSED:', type(parsed), parsed) 12 | t = parsed[:] 13 | print('TUPLE :', type(t), t) 14 | print('NEW :', urlunparse(t)) 15 | -------------------------------------------------------------------------------- /urllib.request/urllib_request_urlopen_iterator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """Simple example with urllib.urlopen(). 7 | """ 8 | 9 | #end_pymotw_header 10 | from urllib import request 11 | 12 | response = request.urlopen('http://localhost:8080/') 13 | for line in response: 14 | print(line.decode('utf-8').rstrip()) 15 | -------------------------------------------------------------------------------- /urllib.robotparser/robots.txt: -------------------------------------------------------------------------------- 1 | 2 | Sitemap: https://pymotw.com/sitemap.xml 3 | User-agent: * 4 | Disallow: /admin/ 5 | Disallow: /downloads/ 6 | Disallow: /media/ 7 | Disallow: /static/ 8 | Disallow: /codehosting/ 9 | -------------------------------------------------------------------------------- /uuid/uuid_getnode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import uuid 8 | 9 | print(hex(uuid.getnode())) 10 | -------------------------------------------------------------------------------- /uuid/uuid_uuid1_othermac.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import uuid 8 | 9 | for node in [0x1ec200d9e0, 0x1e5274040e]: 10 | print(uuid.uuid1(node), hex(node)) 11 | -------------------------------------------------------------------------------- /uuid/uuid_uuid1_repeat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import uuid 8 | 9 | for i in range(3): 10 | print(uuid.uuid1()) 11 | -------------------------------------------------------------------------------- /uuid/uuid_uuid3_uuid5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import uuid 8 | 9 | hostnames = ['www.doughellmann.com', 'blog.doughellmann.com'] 10 | 11 | for name in hostnames: 12 | print(name) 13 | print(' MD5 :', uuid.uuid3(uuid.NAMESPACE_DNS, name)) 14 | print(' SHA-1 :', uuid.uuid5(uuid.NAMESPACE_DNS, name)) 15 | print() 16 | -------------------------------------------------------------------------------- /uuid/uuid_uuid4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | """ 4 | """ 5 | 6 | #end_pymotw_header 7 | import uuid 8 | 9 | for i in range(3): 10 | print(uuid.uuid4()) 11 | -------------------------------------------------------------------------------- /warnings/warnings_filter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import warnings 11 | 12 | warnings.warn('Show this message') 13 | warnings.warn('Do not show this message') 14 | -------------------------------------------------------------------------------- /warnings/warnings_filterwarnings_lineno.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | # flake8: noqa 9 | 10 | #end_pymotw_header 11 | import warnings 12 | 13 | warnings.filterwarnings( 14 | 'ignore', 15 | '.*', 16 | UserWarning, 17 | 'warnings_filter', 18 | 13, 19 | ) 20 | 21 | import warnings_filter 22 | -------------------------------------------------------------------------------- /warnings/warnings_filterwarnings_message.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import warnings 11 | 12 | warnings.filterwarnings('ignore', '.*do not.*',) 13 | 14 | warnings.warn('Show this message') 15 | warnings.warn('Do not show this message') 16 | -------------------------------------------------------------------------------- /warnings/warnings_filterwarnings_module.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | # flake8: noqa 9 | 10 | #end_pymotw_header 11 | import warnings 12 | 13 | warnings.filterwarnings( 14 | 'ignore', 15 | '.*', 16 | UserWarning, 17 | 'warnings_filter', 18 | ) 19 | 20 | import warnings_filter 21 | -------------------------------------------------------------------------------- /warnings/warnings_once.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import warnings 11 | 12 | warnings.simplefilter('once', UserWarning) 13 | 14 | warnings.warn('This is a warning!') 15 | warnings.warn('This is a warning!') 16 | warnings.warn('This is a warning!') 17 | -------------------------------------------------------------------------------- /warnings/warnings_repeated.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import warnings 11 | 12 | 13 | def function_with_warning(): 14 | warnings.warn('This is a warning!') 15 | 16 | 17 | function_with_warning() 18 | function_with_warning() 19 | function_with_warning() 20 | -------------------------------------------------------------------------------- /warnings/warnings_warn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import warnings 11 | 12 | print('Before the warning') 13 | warnings.warn('This is a warning message') 14 | print('After the warning') 15 | -------------------------------------------------------------------------------- /warnings/warnings_warn_raise.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import warnings 11 | 12 | warnings.simplefilter('error', UserWarning) 13 | 14 | print('Before the warning') 15 | warnings.warn('This is a warning message') 16 | print('After the warning') 17 | -------------------------------------------------------------------------------- /warnings/warnings_warn_stacklevel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | 4 | import warnings 5 | 6 | 7 | def old_function(): 8 | warnings.warn( 9 | 'old_function() is deprecated, use new_function()', 10 | stacklevel=2) 11 | 12 | 13 | def caller_of_old_function(): 14 | old_function() 15 | 16 | 17 | caller_of_old_function() 18 | -------------------------------------------------------------------------------- /webbrowser/webbrowser_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import webbrowser 11 | 12 | b = webbrowser.get('lynx') 13 | b.open('https://docs.python.org/3/library/webbrowser.html') 14 | -------------------------------------------------------------------------------- /webbrowser/webbrowser_open.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import webbrowser 11 | 12 | webbrowser.open( 13 | 'https://docs.python.org/3/library/webbrowser.html' 14 | ) 15 | -------------------------------------------------------------------------------- /webbrowser/webbrowser_open_new.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import webbrowser 11 | 12 | webbrowser.open_new( 13 | 'https://docs.python.org/3/library/webbrowser.html' 14 | ) 15 | -------------------------------------------------------------------------------- /webbrowser/webbrowser_open_new_tab.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import webbrowser 11 | 12 | webbrowser.open_new_tab( 13 | 'https://docs.python.org/3/library/webbrowser.html' 14 | ) 15 | -------------------------------------------------------------------------------- /xml.etree.ElementTree/ElementTree_dump_opml.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Dump the OPML in plain text 7 | """ 8 | 9 | #end_pymotw_header 10 | from xml.etree import ElementTree 11 | import pprint 12 | 13 | with open('podcasts.opml', 'rt') as f: 14 | tree = ElementTree.parse(f) 15 | 16 | for node in tree.iter(): 17 | print(node.tag) 18 | -------------------------------------------------------------------------------- /xml.etree.ElementTree/ElementTree_parse_opml.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2010 Doug Hellmann. All rights reserved. 5 | # 6 | """Parse an OPML file and show something about the results. 7 | """ 8 | 9 | #end_pymotw_header 10 | from xml.etree import ElementTree 11 | 12 | with open('podcasts.opml', 'rt') as f: 13 | tree = ElementTree.parse(f) 14 | 15 | print(tree) 16 | -------------------------------------------------------------------------------- /xmlrpc.client/xmlrpc_ServerProxy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import xmlrpc.client 11 | 12 | server = xmlrpc.client.ServerProxy('http://localhost:9000') 13 | print('Ping:', server.ping()) 14 | -------------------------------------------------------------------------------- /xmlrpc.client/xmlrpc_ServerProxy_encoding.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import xmlrpc.client 11 | 12 | server = xmlrpc.client.ServerProxy('http://localhost:9000', 13 | encoding='ISO-8859-1') 14 | print('Ping:', server.ping()) 15 | -------------------------------------------------------------------------------- /xmlrpc.client/xmlrpc_ServerProxy_verbose.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import xmlrpc.client 11 | 12 | server = xmlrpc.client.ServerProxy('http://localhost:9000', 13 | verbose=True) 14 | print('Ping:', server.ping()) 15 | -------------------------------------------------------------------------------- /xmlrpc.server/xmlrpc_arbitrary_name_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import xmlrpc.client 11 | 12 | proxy = xmlrpc.client.ServerProxy('http://localhost:9000') 13 | print(getattr(proxy, 'multiply args')(5, 5)) 14 | -------------------------------------------------------------------------------- /xmlrpc.server/xmlrpc_function_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import xmlrpc.client 11 | 12 | proxy = xmlrpc.client.ServerProxy('http://localhost:9000') 13 | print(proxy.list_contents('/tmp')) 14 | -------------------------------------------------------------------------------- /xmlrpc.server/xmlrpc_instance_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import xmlrpc.client 11 | 12 | proxy = xmlrpc.client.ServerProxy('http://localhost:9000') 13 | print(proxy.list('/tmp')) 14 | -------------------------------------------------------------------------------- /xmlrpc.server/xmlrpc_instance_dotted_names_client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2008 Doug Hellmann All rights reserved. 5 | # 6 | """ 7 | """ 8 | 9 | #end_pymotw_header 10 | import xmlrpc.client 11 | 12 | proxy = xmlrpc.client.ServerProxy('http://localhost:9000') 13 | print(proxy.dir.list('/tmp')) 14 | -------------------------------------------------------------------------------- /zipfile/README.txt: -------------------------------------------------------------------------------- 1 | The examples for the zipfile module use 2 | this file and example.zip as data. 3 | -------------------------------------------------------------------------------- /zipfile/zipfile_is_zipfile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Test if a file is a zipfile. 3 | """ 4 | 5 | #end_pymotw_header 6 | import zipfile 7 | 8 | for filename in ['README.txt', 'example.zip', 9 | 'bad_example.zip', 'notthere.zip']: 10 | print('{:>15} {}'.format( 11 | filename, zipfile.is_zipfile(filename))) 12 | -------------------------------------------------------------------------------- /zipfile/zipfile_namelist.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Reading the names out of a ZIP archive. 3 | """ 4 | 5 | #end_pymotw_header 6 | import zipfile 7 | 8 | with zipfile.ZipFile('example.zip', 'r') as zf: 9 | print(zf.namelist()) 10 | -------------------------------------------------------------------------------- /zipfile/zipfile_printdir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Print the table of contents of a ZIP archive 3 | """ 4 | 5 | #end_pymotw_header 6 | import zipfile 7 | 8 | with zipfile.ZipFile('example.zip', 'r') as zf: 9 | print(zf.printdir()) 10 | -------------------------------------------------------------------------------- /zipfile/zipfile_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Writing data to a new archive. 3 | """ 4 | 5 | #end_pymotw_header 6 | from zipfile_infolist import print_info 7 | import zipfile 8 | 9 | print('creating archive') 10 | with zipfile.ZipFile('write.zip', mode='w') as zf: 11 | print('adding README.txt') 12 | zf.write('README.txt') 13 | 14 | print() 15 | print_info('write.zip') 16 | -------------------------------------------------------------------------------- /zipfile/zipfile_write_arcname.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Writing data to a new archive using an alternate name. 3 | """ 4 | 5 | #end_pymotw_header 6 | from zipfile_infolist import print_info 7 | import zipfile 8 | 9 | with zipfile.ZipFile('write_arcname.zip', mode='w') as zf: 10 | zf.write('README.txt', arcname='NOT_README.txt') 11 | 12 | print_info('write_arcname.zip') 13 | -------------------------------------------------------------------------------- /zipimport/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2007 Doug Hellmann. 3 | # 4 | """Package marker. 5 | 6 | This file is included to cause this directory to be treated as a 7 | python package, instead of a simple directory. 8 | 9 | """ 10 | -------------------------------------------------------------------------------- /zipimport/example_package/README.txt: -------------------------------------------------------------------------------- 1 | This file represents sample data which could be embedded in the 2 | ZIP archive. You could include a configuration file, images, or 3 | any other sort of noncode data. 4 | -------------------------------------------------------------------------------- /zipimport/example_package/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2007 Doug Hellmann. 3 | # 4 | """Example package 5 | 6 | This file represents source code which could be embedded in the 7 | ZIP archive. 8 | 9 | """ 10 | -------------------------------------------------------------------------------- /zipimport/zipimport_find_module.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Finding a module within a zip archive. 6 | """ 7 | 8 | #end_pymotw_header 9 | import zipimport 10 | 11 | importer = zipimport.zipimporter('zipimport_example.zip') 12 | 13 | for module_name in ['zipimport_find_module', 'not_there']: 14 | print(module_name, ':', importer.find_module(module_name)) 15 | -------------------------------------------------------------------------------- /zipimport/zipimport_get_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Retrieving the code for a module within a zip archive. 6 | """ 7 | 8 | #end_pymotw_header 9 | import zipimport 10 | 11 | importer = zipimport.zipimporter('zipimport_example.zip') 12 | code = importer.get_code('zipimport_get_code') 13 | print(code) 14 | -------------------------------------------------------------------------------- /zipimport/zipimport_is_package.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2007 Doug Hellmann. 4 | # 5 | """Determine whether the type of a module within a ZIP archive 6 | """ 7 | 8 | #end_pymotw_header 9 | import zipimport 10 | 11 | importer = zipimport.zipimporter('zipimport_example.zip') 12 | for name in ['zipimport_is_package', 'example_package']: 13 | print(name, importer.is_package(name)) 14 | -------------------------------------------------------------------------------- /zlib/lorem.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec 2 | egestas, enim et consectetuer ullamcorper, lectus ligula rutrum leo, a 3 | elementum elit tortor eu quam. Duis tincidunt nisi ut ante. Nulla 4 | facilisi. Sed tristique eros eu libero. Pellentesque vel arcu. Vivamus 5 | purus orci, iaculis ac, suscipit sit amet, pulvinar eu, 6 | lacus. 7 | --------------------------------------------------------------------------------