K i dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z mZddlmZddlmZddlmZddlmZdd lmZmZdd lmZmZmZmZmZm Z m!Z!dd l"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,dd l-m.Z.dd l/m0Z0ddl1m2Z2m3Z3ddl4m5Z5ddl6m7Z7djqZ9djqZ:e;e dsdge _<dZ=ej|jddZ@e@jdvrdZBn e@jdvrdZBn eCde@ze jxre jjdZFe jde jde jf ZJe jejd!fZMe jHeNe jfZOe je jNeNZQe jNe jeZSd,d"ZTGd#d$eUZVGd%d&ejZXGd'd(eZYeYjZ[eYjZ]d-d.d)Z^d/d*Z_e`d+k(reYjyy)0z,A base class for a configurable application.) annotationsN) OrderedDict defaultdict)suppress)deepcopy) dictConfig)dedent) ConfigurableSingletonConfigurable) ArgumentErrorConfigConfigFileNotFoundDeferredConfigStringJSONFileConfigLoaderKVArgParseConfigLoaderPyFileConfigLoader) BoolDictEnumInstanceList TraitErrorUnicodedefaultobserveobserve_compat)Bunch) nested_update)indentwrap_paragraphs) cast_unicode) import_itemz The options below are convenience aliases to configurable class-options, as listed in the "Equivalent to" description-line of the aliases. To see all configurable class-options for some , use: --help-all z The command-line option below sets the respective configurable class-parameter: --Class.parameter=value This line is evaluated in Python, so simple expressions are allowed. For instance, to set `C.a=[0,1,2]`, you may type this: --C.a='range(3)' argvzp Subcommands are launched as `{app} cmd [args]`. For information on using subcommand 'cmd', do: `{app} cmd -h`. -TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR>1trueT>r%0falseFzUnsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}.z pythonw.exeT.)boundzlogging.LoggerAdapter[t.Any]cttjdfd }tjt|S)aMethod decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input. c |g|i|S#ttf$r]}|jjd||jj d|j |j dYd}~yd}~wwxYw)Nz0Bad config encountered during initialization: %szConfig at the time: %s)rr logfataldebugconfigexit)appargskwargsemethods b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/traitlets/config/application.pyinnerz!catch_config_error..innerssi #/// /M*  GGMMLa P GGMM2CJJ ? HHQKK s A;AA66A;)r5 Applicationr6t.Anyr7r=returnr=) functoolswrapstcastr+)r9r;s` r:catch_config_errorrCjs3__V 66!U c eZdZy)ApplicationErrorN)__name__ __module__ __qualname__rDr:rFrFsrDrFc@eZdZdZej ZdZdfd ZxZ S)LevelFormattera Formatter with additional `highlevel` record This field is empty if log level is less than highlevel_limit, otherwise it is formatted with self.highlevel_format. Useful for adding 'WARNING' to warning messages, without adding 'INFO' to info, etc. z %(levelname)s |c|j|jk\r|j|jz|_nd|_t ||S)Nr%)levelnohighlevel_limithighlevel_format__dict__ highlevelsuperformat)selfrecord __class__s r:rTzLevelFormatter.formatsC >>T11 1#44vFF !F w~f%%rD)rVzlogging.LogRecordr>str) rGrHrI__doc__loggingWARNrOrPrT __classcell__rWs@r:rLrLs#llO)&&rDrLceZdZUdZedZded<edZded<eeZded<ee Z ded<ee Z ded <e Z e ZeZded <gZd ed < dg dhd ZedZded<eZded<eeZedej4dj7dZeZeddj7dZeddj7dZ didZ!e"ddd d!djd"Z#e"d#d$%djd&Z$dkd'Z%e&d#dld(Z'e(d)j7dZ)d*d+iZ*ded,<dd ejViid-fdd.diid/fdd0diid1fd2Z,ded3<e(Z-d4ed5<e.d6d7Z/eeZ0e.e1d8id9Z2eZ3d:ed;<ed<j7dZ4ed=j7dZ5e"d0djd>Z6e"d.djd?Z7dmd@Z8e"dAe9djfdB Z:e;dgdndCZdkdFZ?dodGZ@dkdHZAdodIZBdkdJZCdodKZDdkdLZEdodMZFdpdNZGdqdrdOZHdqdpdPZIdsdQZJdkdRZKdodSZLdkdTZMdodUZNdkdVZOe;dgdtdWZPdudXZQ dvdYZReSdqdwdZZTeSdkd[ZUe;dgdnd\ZVeS dx dyd]ZWeXdzd^ZYe; dg d{d_ZZe;dkd`Z[ dg dhdaZ\dgd|dbZ]dkdcZ^d}d~ddZ_dkdeZ`eSdgddfZaxZbS)r<z8A singleton application with full configuration support. applicationzstr | Unicode[str, str | bytes]namezThis is an application. descriptionoption_descriptionkeyvalue_descriptionsubcommand_descriptionexamples ClassesTypeclassesc#K| |j}t}|D]K}t|jD]-}t |t s||vs|j ||/Myw)aIterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. N)rgsetreversedmro issubclassr add)rUrgseencparents r:_classes_inc_parentsz Application._classes_inc_parentssh ?llGu !A"1557+ !fl3t9KHHV$ L ! !sA A, A,A,z0.0versionzlist[str] | List[str]r$) r (2DEBUGINFOr[ERRORCRITICALz#Set the log level by value or name.) default_valuehelpTr3z%Y-%m-%d %H:%M:%Sz:The date format used by logging formatters for %(asctime)s)r}z#[%(name)s]%(highlevel)s %(message)szThe Logging format templateStrDictc8ddddtj|jddid|jjd|jj |j |jdi|jj ddgd id d }tr|d =|d =|S)aReturn the base logging configuration. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log handler level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. The ``logging_config`` trait is merged into this allowing for finer control of logging. r/consolezlogging.StreamHandlerzext://sys.stderr)class formatterlevelstream.)rrTdatefmtrx)rhandlersF)rrr formattersloggersdisable_existing_loggersrr) rZ getLevelName log_level_log_formatter_clsrHrG log_format log_datefmtrW IS_PYTHONWrUr3s r:get_default_logging_configz&Application.get_default_logging_configs4!*$11$..A0 22==>D33<<=?#oo#//  ''$!* * ).5 : z"y! rDrrrlogging_configc|j}t|tr-tjt t t||_|jyN) r isinstancerXrArBintgetattrrZ_configure_logging)rUchangers r:_observe_logging_changez#Application._observe_logging_changes<NN i %VVC))DEDN !rDr0r)typec$|jyr)rrUrs r:_observe_logging_defaultz$Application._observe_logging_defaults !rDc||j}t||jxsit|d|_y)NT)rrrr_logging_configuredrs r:rzApplication._configure_logging!s5002fd117R86#' rDctj|jj}d|_|}|,|j r|S|js |S|j }|,|S)z#Start logging for this application.F)rZ getLoggerrWrG propagaterrp)rUr0_logs r: _log_defaultzApplication._log_default(se 7 78 }} >> ;;D   rDa! Configure additional log handlers. The default stderr logs handler is configured by the log_level, log_datefmt and log_format settings. This configuration can be used to configure additional handlers (e.g. to output the log to a file) or for finer control over the default handlers. If provided this should be a logging configuration dictionary, for more information see: https://docs.python.org/3/library/logging.config.html#logging-config-dictschema This dictionary is merged with the base logging configuration which defines the following: * A logging formatter intended for interactive use called ``console``. * A logging handler that writes to stderr called ``console`` which uses the formatter ``console``. * A logger with the name of this application set to ``DEBUG`` level. This example adds a new handler that writes to a file: .. code-block:: python c.Application.logging_config = { "handlers": { "file": { "class": "logging.FileHandler", "level": "DEBUG", "filename": "", } }, "loggers": { "": { "level": "DEBUG", # NOTE: if you don't list the default "console" # handler here then it will be disabled "handlers": ["console", "file"], }, }, } z log-levelzApplication.log_levelaliasesz5Set log-level to debug, for the most verbose logging. show_configz>%%' 9C||v%#CLL1 }d3148  9  IIfcjjdD Q JJ  T "   $ $ ( ).. dQh G UI!),L ) &*!T&BN#L1 U $Y/I;c&..*Q.*Q)RST U UrDcTtdj|jy)z"Print the alias parts of the help.rN)rjoinemit_alias_helprs r:print_alias_helpzApplication.print_alias_helps dii,,./0rDc#ZK|jsyi}|jD]R}|jddD]:}tjtj t |||j<<T|jjD]\}} t|tr|\}}nd}|jddd\}}|dz|z}||}|jd|} |j| |j} t|ts|f}t|t }d j#d |D}| d j%d |z|| d <| Ed{t'd |zy7#t($r#} |j*j-d|| d} ~ wwxYww)z+Yield the lines for alias part of the help.NrTr~)helptextkey, c3FK|]}t|dkDrdnd|zywr/z--%sz-%sNlen.0ms r: z.Application.emit_alias_help..!!WASVaZ6Ua"G!W!r--zEquivalent to: [--%s]z7Failed collecting help-message for alias %r, due to: %s)rrgrkrArBTyper rGitemsrtuplesplit class_traitsclass_get_trait_help splitlinesrrrreplacer Exceptionr0error) rU classdictrroaliaslongnamefhelprrtrait fhelp_linesexs r:rzApplication.emit_alias_helps|| 35 << HCWWYs^ H()qvvl/CQ(G !**% H H $||113 OE8 h.&.OHe E'/~~c':23'?$ 9$s?Y6 *(((5i@!66uu6MXXZ !%/"HEu#. !WQV!WW"-Q!7!7x!O A&&&4x?@@+ (' XZ_acd s=BF+CE<"E:#E<7F+:E<< F(F##F((F+cTtdj|jy)z Print the flag part of the help.rN)rremit_flag_helprs r:print_flag_helpzApplication.print_flag_help's dii++-./rDc#K|jsy|jjD]\}\}} t|ts|f}t |t }dj d|D}|tt|jdj d|jD}d|z}tt|y#t$r#}|jjd||d}~wwxYww) z.Yield the lines for the flag part of the help.Nrrc3FK|]}t|dkDrdnd|zywrrrs r:rz-Application.emit_flag_help..5rr c3hK|]*\}}|jD]\}}d|d|d|,yw)rr=N)r)rclname props_dictpropvals r:rz-Application.emit_flag_help..8sQ$* %/%5%5%7$"c$q.$.$s02zEquivalent to: [%s]z6Failed collecting help-message for flag %r, due to: %s) rrrrrrrrr striprr0r)rUrcfgrcfg_listcfg_txtrs r:rzApplication.emit_flag_help+szz #'::#3#3#5  E.sWa//1Ws)rrqrs r:document_config_optionsz#Application.document_config_optionss" yyW4;T;T;VWWWrDcTtdj|jy)z"Print the application description.rN)rrr)rs r:print_descriptionzApplication.print_descriptions dii--/01rDc#tKt|jxs|jxsdD] }|d yw)z-Yield lines with the application description.r%N)r rarY)rUrs r:r)zApplication.emit_descriptions8 !1!1!GT\\!GRH AGH s68cTtdj|jy)z1Print usage and examples (see `emit_examples()`).rN)rrr,rs r:print_exampleszApplication.print_exampless dii**,-.rDc#K|jr?dddtt|jjdyyw)zYield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. Examplesz--------r%N)rerr rrs r:r,zApplication.emit_examplessG ==  H 3 3 567 7H sA Ac.t|jy)zPrint the version string.N)rrrrs r: print_versionzApplication.print_versions dllrDc|jj|}|J|\}}t|tr t |}t|t rBt |tr2|jj|j||_ n't|r|||_ ntd|z|jj|y)z"Initialize a subcommand with argv.N)rpz%Invalid mappings for subcommand '%s'!)rgetrrXr#rrlr<rWclear_instanceinstancercallableAssertionErrorr)rUrr$rrr s r:initialize_subcommandz!Application.initialize_subcommands""4(  fc " (F fd # 6;(G NN ) ) + ///6DK f  ,DK !H4!OP P t$rDc*tt}|jD]D}|j}|j ddD] }||jj |"Fi}|j jD]w\}}t|tr|\}}|jdd\}} ||} t| dk(r| d}t|ts|f}|D]} dj|| g|| <yi} |jjD]y\} \}}i}|jD];\}}||} t| dk(r| d}||vr||j|7|||<=t| ts| f} | D] }||f| |< {| |fS)aFlatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. r/rrr)rlistrgrGrkappendrrrrrrrrupdate)rUmro_treerclsnamerprrrr rchildrenalrrflagdictr}newflagsubdictks r: flatten_flagszApplication.flatten_flagsst$<< :CllG'')Ab/ :)009 : :#%#||113 5OE8(E*& !!Q/JC}H8}!qkgu- 5!hhU|4  5 5%)ZZ%5%5%7 + !C!(D*,G ( 0 + W#C=x=A%"1+C'>CL''0#*GCL +c5)f +#T?a + +"g~rDcLt|||||j|jS)N)rgr0r)rr0r)rUr$rrrgs r:_create_loaderzApplication._create_loaders(& '5'txxTM]M]  rDc|r&dtjvr ddlm}|}|J|St jS#tt f$rYt jSwxYw)aGet `sys.argv` or equivalent from `argcomplete` `argcomplete`'s strategy is to call the python script with no arguments, so ``len(sys.argv) == 1``, and run until the `ArgumentParser` is constructed and determine what completions are available. On the other hand, `traitlet`'s subcommand-handling strategy is to check ``sys.argv[1]`` and see if it matches a subcommand, and if so then dynamically load the subcommand app and initialize it with ``sys.argv[1:]``. This helper method helps to take the current tokens for `argcomplete` and pass them through as `argv`. _ARGCOMPLETEr)get_argcomplete_cwords)osenviron#traitlets.config.argcomplete_configrS ImportErrorModuleNotFoundErrorrr$)rcheck_argcompleterScwordss r: _get_sys_argvzApplication._get_sys_argvsa 2::!= V/1))) xx !45 xx s9AAcpdtjvry ddlm}|y#tt f$rYywxYw)aHelper for `argcomplete` to recognize `traitlets` subcommands `argcomplete` does not know that `traitlets` has already consumed subcommands, as it only "sees" the final `argparse.ArgumentParser` that is constructed. (Indeed `KVArgParseConfigLoader` does not get passed subcommands at all currently.) We explicitly manipulate the environment variables used internally by `argcomplete` to get it to skip over the subcommand tokens. rRNr)increment_argcomplete_index)rTrUrVr]rWrX)rr]s r:"_handle_argcomplete_for_subcommandz.Application._handle_argcomplete_for_subcommand3s9  +   W ' )01   s #55c t|trJ|(|jt|jdd}|Dcgc] }t |c}|_|r|ddk(r |dddgz}|jr^t|dkDrP|d|dd}}tjd|r0||jvr"|j|j||S |d|jd t fd d Dr$|jd v|j!dd vsd vr!|j#|j!d|j%\}}t'|j)}|j+||||} t-|j/|_|j5|j0|j6|_ycc}w#t$r| YwxYw#t2$rwxYw)z!Parse the command line arguments.N)rYr/rr}-hz ^\w(\-?\w)*$rc3&K|]}|v ywrrJ)rxinterpreted_argvs r:rz1Application.parse_command_line..dsMq$$Ms)r` --help-allz--helprdz --versionz-Vr%)rrXr[boolrr"r$rrematchr^rAindex ValueErroranyr'r4r:rNrCr*rPr load_config cli_config SystemExit update_config extra_args) rUr$argrsubargvrrrgloaderrcs @r:rzApplication.parse_command_lineGsdC((( <%%T=M=M8N%OPQPRSD2673\#&7 DGv%8tf$D   D A  GT!"X'Dxx.44;K;K3K77911$@@  $#$6djj&67  M.LM M OOL,<< = IIaL * *d6F.F    IIaL++-wt779:$$T7E7$K &v'9'9';c #dKt|ts||g}t|D]F}|j|dz||}|r)|j d||xst j |j|dz||}g}g} ||fD]} d} | j} |r|j d| j | s8t| |D]]\} } | j| }|s|s|jd j!| | jt#j$|d _| | jf|j'| | j'| jIy#t$rYt$r,| jxs|} |r|r|jd| d YwxYww) zeLoad config files (py,json) by filename and path. yield each config object in turn. Nz.py)pathr0zLooking for %s in %sz.jsonzLoaded config file: %sz&Exception while loading config file %sT)exc_infozMCollisions detected in {0} and {1} config files. {1} has higher priority: {2}r!)r)rrXrjpython_config_loader_classr2rTgetcwdjson_config_loader_classrk full_filenamerrrzip collisionswarningrTrdumpsrD)r basefilenamertr0raise_config_file_errorscurrentpyloader jsonloaderloaded filenamesrrr3filenameearlier_configr{s r:_load_config_fileszApplication._load_config_fileszs dC DL6D~( ;G55lU6JQX^a5bH 0,@V299;W55lW6LSZ`c5dJ"$F#%I#Z0 ;R#//1F ":F%>v%F %#KK!@@F$,$*$8$8$(JJz!$DA" "6#7#788MM&)$$V%9%9:A ;( ;* e &33C|H/ "JH_c desIB F0E.!F0%F0&F0)BF0. F-7F091F-*F0,F--F0c |jddS)z$Currently loaded configuration filesN)rrs r:loaded_config_fileszApplication.loaded_config_filess((++rDctjj|\}}t}|j |||j |j D]@\}}|j|||jvs&|jj|B|j|j|j|y)z'Load config files by filename and path.)rtr0rN) rTrtsplitextr rr0rmergerrDrlrn)rUrrtext new_configr3fnames r:load_config_filezApplication.load_config_files ((2 #X !44 %)%B%B 5 8MFE   V $T666))007 8 ) :&rDc|jjjdd}t}|jj d|t jjD]m\}}|j|s|jj d|||jd^}}}|}|D]} || } t||t|o|j|j|j|y)z!Load config files by environment.-r z1Looping through config variables with prefix "%s"zSeeing environ "%s"="%s"__N)r`upperrr r0r2rTrUr startswithrsetattrrrrlrn) rUPREFIXrrMvr rtrsectionrs r:load_config_environzApplication.load_config_environs"**34X  JFSJJ$$& ?DAq||F#91a@!" D#$)A%ajG)&:1&=> ? ) :&rDc#,K| |j}td|j|Ddfd  j}tfdj D|k(rn9j D] \}}|s |yw)a Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. Nc3VK|]!}|t|jdf#yw)Tr~N)reclass_own_traits)rrs r:rz:Application._classes_with_config_traits..s0$ $s++4+89 :$ s')c@tfd|jDS)Nc34K|]}|vxr|ywrrJ)rb cls_to_configs r:rzZApplication._classes_with_config_traits..is_any_parent_included..s#V1qM)>mA.>>Vs)rj __bases__)rrs r:is_any_parent_includedzGApplication._classes_with_config_traits..is_any_parent_includedsV VV VrDc3@K|]\}}||xs|fywrrJ)rrinc_yesrs r:rz:Application._classes_with_config_traits..s-( Cgre)rgrrqrr)rUrg to_incl_origclrrrs @@r:r*z'Application._classes_with_config_traitss ?llG#$ 009$   W (--/L'($1$7$7$9(M ,)..0 KB s BB BcLd|jzg}|jd|jd|jd| |jn|}t|j |}|D]"}|j|j |$dj |S)z/generate default config file from Configurablesz# Configuration file for %s.r%zc = get_config() #noqar)r`rDrgrCr*class_config_sectionr)rUrglinesconfig_classesrs r:generate_config_filez Application.generate_config_file s/$));< R 34 R")/$,,wd>>wGH! CC LL11.A B CyyrDct|ddrK|jjD]*}tt5|j ddd,d|_yy#1swY?xYw)NrF)rr0rrrcloser)rUhandlers r:close_handlerszApplication.close_handlerssd 4. 6 88,, $i($MMO$$ $(-D $ 7 $$s AA# c|jjd|j|jt j |y)NzExiting application: %s)r0r2r`rrr4)rU exit_statuss r:r4zApplication.exit#s1 0$))<  rDc$|jyr)rrs r:__del__zApplication.__del__(s rDc j|jdi|}|j||jy)zLaunch a global instance of this Application If a global instance already exists, this reinitializes and starts it NrJ)r>rr)rr$r7r5s r:launch_instancezApplication.launch_instance+s, cll$V$ t rDr)rgClassesType | Noner>z+t.Generator[type[Configurable], None, None])r>r)rrr>None)r>r)r> AnyLogger)r7r=r>r)r$ArgvTyper>r)r>t.Generator[str, None, None])rgrer>r)F)rgrer>r)r>rX)rrXr$rr>r)r>z)tuple[dict[str, t.Any], dict[str, t.Any]]) r$zlist[str] | Nonerrrrrgrr>r)rYrer> list[str])NF) r~rXrt#str | t.Sequence[str | None] | Noner0zAnyLogger | Nonerrer>zt.Generator[t.Any, None, None])r>r)rrXrtrr>r)rgrr>rX)r)rzint | str | Noner>r)r$rr7r=r>r)crGrHrIrYrr`__annotations__rarbrcrdrrvrrxrergrqrrrr$rr&rrrZr[tagrrLrrrrrrrrrrrrrrxrrrrror rlrrrrrrrrrCrrrrrrrrrrrr#r'r&r1r3r)r6r,r:rArNrP classmethodr[r^rrpropertyrrrr*rrr4rrr\r]s@r:r<r<sB-4M,BD )B4;;T3UK0U:ABT:U7UEF\>];]!3318 H-9G[-1!)! 4!.07u~G ,=#'&D ( $$QRMll 2 cc  ("^ cc- * cc 1f ]L+7GH"I" U#"$"( U^  . 0` ccan$%<=GW=   D  !4   K  &   A  #E7@8so*7=<7H<~ r3r rJrDr: get_configr]s,  ##%,,,xrD__main__)r9r+r>r+)r%r%) r`rXrrXrrXrrXr>r)r>r )brY __future__rr?rrZrTrrfrtypingrA collectionsrr contextlibrrrlogging.configrtextwrapr traitlets.config.configurabler r traitlets.config.loaderr r rrrrrtraitlets.traitletsrrrrrrrrrrtraitlets.utils.bunchrtraitlets.utils.nested_updatertraitlets.utils.textrr utilsr"utils.importstringr#rrbrchasattrr$rdrUr<_envvarlowerr&ri executableendswithrTypeVarCallableAnyr+UnionLoggerrrXrOptionalrrrfrCrrF FormatterrLr<rdefault_aliasesr default_flagsrrrGrrJrDr:rs2#  0%M   (78 ,   EG   EG sFtCH **..H" M ==?m#481 ]]_**491  h    ^^ F 7 7 F  AIIcCJ/0 GGGNN$BB C &&aee  ::affSk "ffQVVL)* * y &W&&&*['[D%%!! L> z!rD