IDLE — Python 3.10.6 documentation

文章推薦指數: 80 %
投票人數:10人

IDLE has two main window types, the Shell window and the Editor window. It is possible to have multiple editor windows simultaneously. On Windows and Linux, ... Navigation index modules| next| previous| Python» 3.10.6Documentation» ThePythonStandardLibrary» GraphicalUserInterfaceswithTk» IDLE | IDLE¶ Sourcecode:Lib/idlelib/ IDLEisPython’sIntegratedDevelopmentandLearningEnvironment. IDLEhasthefollowingfeatures: codedin100%purePython,usingthetkinterGUItoolkit cross-platform:worksmostlythesameonWindows,Unix,andmacOS Pythonshellwindow(interactiveinterpreter)withcolorizing ofcodeinput,output,anderrormessages multi-windowtexteditorwithmultipleundo,Pythoncolorizing, smartindent,calltips,autocompletion,andotherfeatures searchwithinanywindow,replacewithineditorwindows,andsearch throughmultiplefiles(grep) debuggerwithpersistentbreakpoints,stepping,andviewing ofglobalandlocalnamespaces configuration,browsers,andotherdialogs Menus¶ IDLEhastwomainwindowtypes,theShellwindowandtheEditorwindow.Itis possibletohavemultipleeditorwindowssimultaneously.OnWindowsand Linux,eachhasitsowntopmenu.Eachmenudocumentedbelowindicates whichwindowtypeitisassociatedwith. Outputwindows,suchasusedforEdit=>FindinFiles,areasubtypeofeditor window.Theycurrentlyhavethesametopmenubutadifferent defaulttitleandcontextmenu. OnmacOS,thereisoneapplicationmenu.Itdynamicallychangesaccording tothewindowcurrentlyselected.IthasanIDLEmenu,andsomeentries describedbelowaremovedaroundtoconformtoAppleguidelines. Filemenu(ShellandEditor)¶ NewFileCreateanewfileeditingwindow. Open…OpenanexistingfilewithanOpendialog. OpenModule…Openanexistingmodule(searchessys.path). RecentFilesOpenalistofrecentfiles.Clickonetoopenit. ModuleBrowserShowfunctions,classes,andmethodsinthecurrentEditorfileina treestructure.Intheshell,openamodulefirst. PathBrowserShowsys.pathdirectories,modules,functions,classesandmethodsina treestructure. SaveSavethecurrentwindowtotheassociatedfile,ifthereisone.Windows thathavebeenchangedsincebeingopenedorlastsavedhavea*before andafterthewindowtitle.Ifthereisnoassociatedfile, doSaveAsinstead. SaveAs…SavethecurrentwindowwithaSaveAsdialog.Thefilesavedbecomesthe newassociatedfileforthewindow.(Ifyourfilenamagerissettohide extensions,thecurrentextensionwillbeomittedinthefilenamebox. Ifthenewfilenamehasno‘.’,‘.py’and‘.txt’willbeaddedforPython andtextfiles,exceptthatonmacOSAqua,’.py’isaddedforallfiles.) SaveCopyAs…Savethecurrentwindowtodifferentfilewithoutchangingtheassociated file.(SeeSaveAsnoteaboveaboutfilenameextensions.) PrintWindowPrintthecurrentwindowtothedefaultprinter. CloseWindowClosethecurrentwindow(ifanunsavededitor,asktosave;ifanunsaved Shell,asktoquitexecution).Callingexit()orclose()intheShell windowalsoclosesShell.Ifthisistheonlywindow,alsoexitIDLE. ExitIDLECloseallwindowsandquitIDLE(asktosaveunsavededitwindows). Editmenu(ShellandEditor)¶ UndoUndothelastchangetothecurrentwindow.Amaximumof1000changesmay beundone. RedoRedothelastundonechangetothecurrentwindow. SelectAllSelecttheentirecontentsofthecurrentwindow. CutCopyselectionintothesystem-wideclipboard;thendeletetheselection. CopyCopyselectionintothesystem-wideclipboard. PasteInsertcontentsofthesystem-wideclipboardintothecurrentwindow. Theclipboardfunctionsarealsoavailableincontextmenus. Find…Openasearchdialogwithmanyoptions FindAgainRepeatthelastsearch,ifthereisone. FindSelectionSearchforthecurrentlyselectedstring,ifthereisone. FindinFiles…Openafilesearchdialog.Putresultsinanewoutputwindow. Replace…Openasearch-and-replacedialog. GotoLineMovethecursortothebeginningofthelinerequestedandmakethat linevisible.Arequestpasttheendofthefilegoestotheend. Clearanyselectionandupdatethelineandcolumnstatus. ShowCompletionsOpenascrollablelistallowingselectionofexistingnames.See CompletionsintheEditingandnavigationsectionbelow. ExpandWordExpandaprefixyouhavetypedtomatchafullwordinthesamewindow; repeattogetadifferentexpansion. ShowCallTipAfteranunclosedparenthesisforafunction,openasmallwindowwith functionparameterhints.SeeCalltipsinthe Editingandnavigationsectionbelow. ShowSurroundingParensHighlightthesurroundingparenthesis. Formatmenu(Editorwindowonly)¶ FormatParagraphReformatthecurrentblank-line-delimitedparagraphincommentblockor multilinestringorselectedlineinastring.Alllinesinthe paragraphwillbeformattedtolessthanNcolumns,whereNdefaultsto72. IndentRegionShiftselectedlinesrightbytheindentwidth(default4spaces). DedentRegionShiftselectedlinesleftbytheindentwidth(default4spaces). CommentOutRegionInsert##infrontofselectedlines. UncommentRegionRemoveleading#or##fromselectedlines. TabifyRegionTurnleadingstretchesofspacesintotabs.(Note:Werecommendusing 4spaceblockstoindentPythoncode.) UntabifyRegionTurnalltabsintothecorrectnumberofspaces. ToggleTabsOpenadialogtoswitchbetweenindentingwithspacesandtabs. NewIndentWidthOpenadialogtochangeindentwidth.TheaccepteddefaultbythePython communityis4spaces. StripTrailingChitespaceRemovetrailingspaceandotherwhitespacecharactersafterthelast non-whitespacecharacterofalinebyapplyingstr.rstriptoeachline, includinglineswithinmultilinestrings.ExceptforShellwindows, removeextranewlinesattheendofthefile. Runmenu(Editorwindowonly)¶ RunModuleDoCheckModule.Ifnoerror,restarttheshelltocleanthe environment,thenexecutethemodule.OutputisdisplayedintheShell window.Notethatoutputrequiresuseofprintorwrite. Whenexecutioniscomplete,theShellretainsfocusanddisplaysaprompt. Atthispoint,onemayinteractivelyexploretheresultofexecution. Thisissimilartoexecutingafilewithpython-ifileatacommand line. Run…CustomizedSameasRunModule,butrunthemodulewithcustomized settings.CommandLineArgumentsextendsys.argvasifpassed onacommandline.ThemodulecanberunintheShellwithoutrestarting. CheckModuleCheckthesyntaxofthemodulecurrentlyopenintheEditorwindow.Ifthe modulehasnotbeensavedIDLEwilleitherprompttheusertosaveor autosave,asselectedintheGeneraltaboftheIdleSettingsdialog.If thereisasyntaxerror,theapproximatelocationisindicatedinthe Editorwindow. PythonShellOpenorwakeupthePythonShellwindow. Shellmenu(Shellwindowonly)¶ ViewLastRestartScrolltheshellwindowtothelastShellrestart. RestartShellRestarttheshelltocleantheenvironmentandresetdisplayandexceptionhandling. PreviousHistoryCyclethroughearliercommandsinhistorywhichmatchthecurrententry. NextHistoryCyclethroughlatercommandsinhistorywhichmatchthecurrententry. InterruptExecutionStoparunningprogram. Debugmenu(Shellwindowonly)¶ GotoFile/LineLookonthecurrentline.withthecursor,andthelineaboveforafilename andlinenumber.Iffound,openthefileifnotalreadyopen,andshowthe line.Usethistoviewsourcelinesreferencedinanexceptiontraceback andlinesfoundbyFindinFiles.Alsoavailableinthecontextmenuof theShellwindowandOutputwindows. Debugger(toggle)Whenactivated,codeenteredintheShellorrunfromanEditorwillrun underthedebugger.IntheEditor,breakpointscanbesetwiththecontext menu.Thisfeatureisstillincompleteandsomewhatexperimental. StackViewerShowthestacktracebackofthelastexceptioninatreewidget,with accesstolocalsandglobals. Auto-openStackViewerToggleautomaticallyopeningthestackvieweronanunhandledexception. Optionsmenu(ShellandEditor)¶ ConfigureIDLEOpenaconfigurationdialogandchangepreferencesforthefollowing: fonts,indentation,keybindings,textcolorthemes,startupwindowsand size,additionalhelpsources,andextensions.OnmacOS,openthe configurationdialogbyselectingPreferencesintheapplication menu.Formoredetails,see SettingpreferencesunderHelpandpreferences. Mostconfigurationoptionsapplytoallwindowsorallfuturewindows. Theoptionitemsbelowonlyapplytotheactivewindow. Show/HideCodeContext(EditorWindowonly)Openapaneatthetopoftheeditwindowwhichshowstheblockcontext ofthecodewhichhasscrolledabovethetopofthewindow.See CodeContextintheEditingandNavigationsection below. Show/HideLineNumbers(EditorWindowonly)Openacolumntotheleftoftheeditwindowwhichshowsthenumber ofeachlineoftext.Thedefaultisoff,whichmaybechangedinthe preferences(seeSettingpreferences). Zoom/RestoreHeightTogglesthewindowbetweennormalsizeandmaximumheight.Theinitialsize defaultsto40linesby80charsunlesschangedontheGeneraltabofthe ConfigureIDLEdialog.Themaximumheightforascreenisdeterminedby momentarilymaximizingawindowthefirsttimeoneiszoomedonthescreen. Changingscreensettingsmayinvalidatethesavedheight.Thistogglehas noeffectwhenawindowismaximized. Windowmenu(ShellandEditor)¶ Liststhenamesofallopenwindows;selectonetobringittotheforeground (deiconifyingitifnecessary). Helpmenu(ShellandEditor)¶ AboutIDLEDisplayversion,copyright,license,credits,andmore. IDLEHelpDisplaythisIDLEdocument,detailingthemenuoptions,basiceditingand navigation,andothertips. PythonDocsAccesslocalPythondocumentation,ifinstalled,orstartawebbrowser andopendocs.python.orgshowingthelatestPythondocumentation. TurtleDemoRuntheturtledemomodulewithexamplePythoncodeandturtledrawings. AdditionalhelpsourcesmaybeaddedherewiththeConfigureIDLEdialogunder theGeneraltab.SeetheHelpsourcessubsectionbelow formoreonHelpmenuchoices. Contextmenus¶ Openacontextmenubyright-clickinginawindow(Control-clickonmacOS). ContextmenushavethestandardclipboardfunctionsalsoontheEditmenu. CutCopyselectionintothesystem-wideclipboard;thendeletetheselection. CopyCopyselectionintothesystem-wideclipboard. PasteInsertcontentsofthesystem-wideclipboardintothecurrentwindow. Editorwindowsalsohavebreakpointfunctions.Lineswithabreakpointsetare speciallymarked.Breakpointsonlyhaveaneffectwhenrunningunderthe debugger.Breakpointsforafilearesavedintheuser’s.idlerc directory. SetBreakpointSetabreakpointonthecurrentline. ClearBreakpointClearthebreakpointonthatline. ShellandOutputwindowsalsohavethefollowing. Gotofile/lineSameasinDebugmenu. TheShellwindowalsohasanoutputsqueezingfacilityexplainedinthePython Shellwindowsubsectionbelow. SqueezeIfthecursorisoveranoutputline,squeezealltheoutputbetween thecodeaboveandthepromptbelowdowntoa‘Squeezedtext’label. EditingandNavigation¶ Editorwindows¶ IDLEmayopeneditorwindowswhenitstarts,dependingonsettings andhowyoustartIDLE.Thereafter,usetheFilemenu.Therecanbeonly oneopeneditorwindowforagivenfile. Thetitlebarcontainsthenameofthefile,thefullpath,andtheversion ofPythonandIDLErunningthewindow.Thestatusbarcontainstheline number(‘Ln’)andcolumnnumber(‘Col’).Linenumbersstartwith1; columnnumberswith0. IDLEassumesthatfileswithaknown.py*extensioncontainPythoncode andthatotherfilesdonot.RunPythoncodewiththeRunmenu. Keybindings¶ Inthissection,‘C’referstotheControlkeyonWindowsandUnixand theCommandkeyonmacOS. Backspacedeletestotheleft;Deldeletestotheright C-Backspacedeletewordleft;C-Deldeletewordtotheright ArrowkeysandPageUp/PageDowntomovearound C-LeftArrowandC-RightArrowmovesbywords Home/Endgotobegin/endofline C-Home/C-Endgotobegin/endoffile SomeusefulEmacsbindingsareinheritedfromTcl/Tk: C-abeginningofline C-eendofline C-kkillline(butdoesn’tputitinclipboard) C-lcenterwindowaroundtheinsertionpoint C-bgobackwardonecharacterwithoutdeleting(usuallyyoucan alsousethecursorkeyforthis) C-fgoforwardonecharacterwithoutdeleting(usuallyyoucan alsousethecursorkeyforthis) C-pgouponeline(usuallyyoucanalsousethecursorkeyfor this) C-ddeletenextcharacter Standardkeybindings(likeC-ctocopyandC-vtopaste) maywork.KeybindingsareselectedintheConfigureIDLEdialog. Automaticindentation¶ Afterablock-openingstatement,thenextlineisindentedby4spaces(inthe PythonShellwindowbyonetab).Aftercertainkeywords(break,returnetc.) thenextlineisdedented.Inleadingindentation,Backspacedeletesup to4spacesiftheyarethere.Tabinsertsspaces(inthePython Shellwindowonetab),numberdependsonIndentwidth.Currently,tabs arerestrictedtofourspacesduetoTcl/Tklimitations. Seealsotheindent/dedentregioncommandsonthe Formatmenu. SearchandReplace¶ Anyselectionbecomesasearchtarget.However,onlyselectionswithin alineworkbecausesearchesareonlyperformedwithinlineswiththe terminalnewlineremoved.If[x]Regularexpresionischecked,the targetisinterpretedaccordingtothePythonremodule. Completions¶ Completionsaresupplied,whenrequestedandavailable,formodule names,attributesofclassesorfunctions,orfilenames.Eachrequest methoddisplaysacompletionboxwithexistingnames.(Seetab completionsbelowforanexception.)Foranybox,changethename beingcompletedandtheitemhighlightedintheboxby typinganddeletingcharacters;byhittingUp,Down, PageUp,PageDown,Home,andEndkeys; andbyasingleclickwithinthebox.ClosetheboxwithEscape, Enter,anddoubleTabkeysorclicksoutsidethebox. Adoubleclickwithintheboxselectsandcloses. Onewaytoopenaboxistotypeakeycharacterandwaitfora predefinedinterval.Thisdefaultsto2seconds;customizeit inthesettingsdialog.(Topreventautopopups,setthedelaytoa largenumberofmilliseconds,suchas100000000.)Forimportedmodule namesorclassorfunctionattributes,type‘.’. Forfilenamesintherootdirectory,typeos.sepor os.altsepimmediatelyafteranopeningquote.(OnWindows, onecanspecifyadrivefirst.)Moveintosubdirectoriesbytypinga directorynameandaseparator. Insteadofwaiting,orafteraboxisclosed,openacompletionbox immediatelywithShowCompletionsontheEditmenu.Thedefaulthot keyisC-space.Ifonetypesaprefixforthedesiredname beforeopeningthebox,thefirstmatchornearmissismadevisible. Theresultisthesameasifoneentersaprefix aftertheboxisdisplayed.ShowCompletionsafteraquotecompletes filenamesinthecurrentdirectoryinsteadofarootdirectory. HittingTabafteraprefixusuallyhasthesameeffectasShow Completions.(Withnoprefix,itindents.)However,ifthereisonly onematchtotheprefix,thatmatchisimmediatelyaddedtotheeditor textwithoutopeningabox. Invoking‘ShowCompletions’,orhittingTabafteraprefix, outsideofastringandwithoutapreceding‘.’opensaboxwith keywords,builtinnames,andavailablemodule-levelnames. Wheneditingcodeinaneditor(asopposetoShell),increasethe availablemodule-levelnamesbyrunningyourcode andnotrestartingtheShellthereafter.Thisisespeciallyuseful afteraddingimportsatthetopofafile.Thisalsoincreases possibleattributecompletions. Completionboxesinitiallyexcludenamesbeginningwith‘_’or,for modules,notincludedin‘__all__’.Thehiddennamescanbeaccessed bytyping‘_’after‘.’,eitherbeforeoraftertheboxisopened. Calltips¶ Acalltipisshownautomaticallywhenonetypes(afterthename ofanaccessiblefunction.Afunctionnameexpressionmayinclude dotsandsubscripts.Acalltipremainsuntilitisclicked,thecursor ismovedoutoftheargumentarea,or)istyped.Wheneverthe cursorisintheargumentpartofadefinition,selectEditand“Show CallTip”onthemenuorenteritsshortcuttodisplayacalltip. Thecalltipconsistsofthefunction’ssignatureanddocstringupto thelatter’sfirstblanklineorthefifthnon-blankline.(Somebuiltin functionslackanaccessiblesignature.)A‘/’or‘*’inthesignature indicatesthattheprecedingorfollowingargumentsarepassedby positionorname(keyword)only.Detailsaresubjecttochange. InShell,theaccessiblefunctionsdependsonwhatmoduleshavebeen importedintotheuserprocess,includingthoseimportedbyIdleitself, andwhichdefinitionshavebeenrun,allsincethelastrestart. Forexample,restarttheShellandenteritertools.count(.Acalltip appearsbecauseIdleimportsitertoolsintotheuserprocessforitsown use.(Thiscouldchange.)Enterturtle.write(andnothingappears. Idledoesnotitselfimportturtle.Themenuentryandshortcutalsodo nothing.Enterimportturtle.Thereafter,turtle.write( willdisplayacalltip. Inaneditor,importstatementshavenoeffectuntilonerunsthefile. Onemightwanttorunafileafterwritingimportstatements,after addingfunctiondefinitions,orafteropeninganexistingfile. CodeContext¶ WithinaneditorwindowcontainingPythoncode,codecontextcanbetoggled inordertoshoworhideapaneatthetopofthewindow.Whenshown,this panefreezestheopeninglinesforblockcode,suchasthosebeginningwith class,def,orifkeywords,thatwouldhaveotherwisescrolled outofview.Thesizeofthepanewillbeexpandedandcontractedasneeded toshowtheallcurrentlevelsofcontext,uptothemaximumnumberof linesdefinedintheConfigureIDLEdialog(whichdefaultsto15).Ifthere arenocurrentcontextlinesandthefeatureistoggledon,asingleblank linewilldisplay.Clickingonalineinthecontextpanewillmovethat linetothetopoftheeditor. Thetextandbackgroundcolorsforthecontextpanecanbeconfiguredunder theHighlightstabintheConfigureIDLEdialog. Shellwindow¶ InIDLE’sShell,enter,edit,andrecallcompletestatements.(Most consolesandterminalsonlyworkwithasinglephysicallineatatime). Submitasingle-linestatementforexecutionbyhittingReturn withthecursoranywhereontheline.Ifalineisextendedwith Backslash(\),thecursormustbeonthelastphysicalline. Submitamulti-linecompoundstatementbyenteringablanklineafter thestatement. WhenonepastescodeintoShell,itisnotcompiledandpossiblyexecuted untilonehitsReturn,asspecifiedabove. Onemayeditpastedcodefirst. IfonepastesmorethanonestatementintoShell,theresultwillbea SyntaxErrorwhenmultiplestatementsarecompiledasiftheywereone. LinescontainingRESTARTmeanthattheuserexecutionprocesshasbeen re-started.Thisoccurswhentheuserexecutionprocesshascrashed, whenonerequestsarestartontheShellmenu,orwhenonerunscode inaneditorwindow. Theeditingfeaturesdescribedinprevioussubsectionsworkwhenentering codeinteractively.IDLE’sShellwindowalsorespondstothefollowingkeys. C-cinterruptsexecutingcommand C-dsendsend-of-file;closeswindowiftypedata>>>prompt Alt-/(Expandword)isalsousefultoreducetyping Commandhistory Alt-pretrievespreviouscommandmatchingwhatyouhavetyped.On macOSuseC-p. Alt-nretrievesnext.OnmacOSuseC-n. Returnwhilethecursorisonanypreviouscommand retrievesthatcommand Textcolors¶ Idledefaultstoblackonwhitetext,butcolorstextwithspecialmeanings. Fortheshell,theseareshelloutput,shellerror,useroutput,and usererror.ForPythoncode,attheshellpromptorinaneditor,theseare keywords,builtinclassandfunctionnames,namesfollowingclassand def,strings,andcomments.Foranytextwindow,thesearethecursor(when present),foundtext(whenpossible),andselectedtext. IDLEalsohighlightsthesoftkeywordsmatch, case,and_in pattern-matchingstatements.However,thishighlightingisnotperfectand willbeincorrectinsomerarecases,includingsome_-sincase patterns. Textcoloringisdoneinthebackground,souncolorizedtextisoccasionally visible.Tochangethecolorscheme,usetheConfigureIDLEdialog Highlightingtab.Themarkingofdebuggerbreakpointlinesintheeditorand textinpopupsanddialogsisnotuser-configurable. StartupandCodeExecution¶ Uponstartupwiththe-soption,IDLEwillexecutethefilereferencedby theenvironmentvariablesIDLESTARTUPorPYTHONSTARTUP. IDLEfirstchecksforIDLESTARTUP;ifIDLESTARTUPispresentthefile referencedisrun.IfIDLESTARTUPisnotpresent,IDLEchecksfor PYTHONSTARTUP.Filesreferencedbytheseenvironmentvariablesare convenientplacestostorefunctionsthatareusedfrequentlyfromtheIDLE shell,orforexecutingimportstatementstoimportcommonmodules. Inaddition,Tkalsoloadsastartupfileifitispresent.Notethatthe Tkfileisloadedunconditionally.Thisadditionalfileis.Idle.pyandis lookedforintheuser’shomedirectory.Statementsinthisfilewillbe executedintheTknamespace,sothisfileisnotusefulforimporting functionstobeusedfromIDLE’sPythonshell. Commandlineusage¶ idle.py[-ccommand][-d][-e][-h][-i][-rfile][-s][-ttitle][-][arg]... -ccommandruncommandintheshellwindow -denabledebuggerandopenshellwindow -eopeneditorwindow -hprinthelpmessagewithlegalcombinationsandexit -iopenshellwindow -rfilerunfileinshellwindow -srun$IDLESTARTUPor$PYTHONSTARTUPfirst,inshellwindow -ttitlesettitleofshellwindow -runstdininshell(-mustbelastoptionbeforeargs) Iftherearearguments: If-,-c,orrisused,allargumentsareplacedin sys.argv[1:...]andsys.argv[0]issetto'','-c', or'-r'.Noeditorwindowisopened,evenifthatisthedefault setintheOptionsdialog. Otherwise,argumentsarefilesopenedforeditingand sys.argvreflectstheargumentspassedtoIDLEitself. Startupfailure¶ IDLEusesasockettocommunicatebetweentheIDLEGUIprocessandtheuser codeexecutionprocess.AconnectionmustbeestablishedwhenevertheShell startsorrestarts.(Thelatterisindicatedbyadividerlinethatsays ‘RESTART’).IftheuserprocessfailstoconnecttotheGUIprocess,it usuallydisplaysaTkerrorboxwitha‘cannotconnect’message thatdirectstheuserhere.Itthenexits. OnespecificconnectionfailureonUnixsystemsresultsfrom misconfiguredmasqueradingrulessomewhereinasystem’snetworksetup. WhenIDLEisstartedfromaterminal,onewillseeamessagestarting with**Invalidhost:. Thevalidvalueis127.0.0.1(idlelib.rpc.LOCALHOST). Onecandiagnosewithtcpconnect-irv127.0.0.16543inone terminalwindowandtcplisteninanother. Acommoncauseoffailureisauser-writtenfilewiththesamenameasa standardlibrarymodule,suchasrandom.pyandtkinter.py.Whensucha fileislocatedinthesamedirectoryasafilethatisabouttoberun, IDLEcannotimportthestdlibfile.Thecurrentfixistorenamethe userfile. Thoughlesscommonthaninthepast,anantivirusorfirewallprogrammay stoptheconnection.Iftheprogramcannotbetaughttoallowthe connection,thenitmustbeturnedoffforIDLEtowork.Itissafeto allowthisinternalconnectionbecausenodataisvisibleonexternal ports.Asimilarproblemisanetworkmis-configurationthatblocks connections. PythoninstallationissuesoccasionallystopIDLE:multipleversionscan clash,orasingleinstallationmightneedadminaccess.Ifoneundothe clash,orcannotordoesnotwanttorunasadmin,itmightbeeasiestto completelyremovePythonandstartover. Azombiepythonw.exeprocesscouldbeaproblem.OnWindows,useTask Managertocheckforoneandstopitifthereis.Sometimesarestart initiatedbyaprogramcrashorKeyboardInterrupt(control-C)mayfail toconnect.DismissingtheerrorboxorusingRestartShellontheShell menumayfixatemporaryproblem. WhenIDLEfirststarts,itattemptstoreaduserconfigurationfilesin ~/.idlerc/(~isone’shomedirectory).Ifthereisaproblem,anerror messageshouldbedisplayed.Leavingasiderandomdiskglitches,thiscan bepreventedbynevereditingthefilesbyhand.Instead,usethe configurationdialog,underOptions.Oncethereisanerrorinauser configurationfile,thebestsolutionmaybetodeleteitandstartover withthesettingsdialog. IfIDLEquitswithnomessage,anditwasnotstartedfromaconsole,try startingitfromaconsoleorterminal(python-midlelib)andseeif thisresultsinanerrormessage. OnUnix-basedsystemswithtcl/tkolderthan8.6.11(see AboutIDLE)certaincharactersofcertainfontscancause atkfailurewithamessagetotheterminal.Thiscanhappeneither ifonestartsIDLEtoeditafilewithsuchacharacterorlater whenenteringsuchacharacter.Ifonecannotupgradetcl/tk, thenre-configureIDLEtouseafontthatworksbetter. Runningusercode¶ Withrareexceptions,theresultofexecutingPythoncodewithIDLEis intendedtobethesameasexecutingthesamecodebythedefaultmethod, directlywithPythoninatext-modesystemconsoleorterminalwindow. However,thedifferentinterfaceandoperationoccasionallyaffect visibleresults.Forinstance,sys.modulesstartswithmoreentries, andthreading.active_count()returns2insteadof1. Bydefault,IDLErunsusercodeinaseparateOSprocessratherthanin theuserinterfaceprocessthatrunstheshellandeditor.Intheexecution process,itreplacessys.stdin,sys.stdout,andsys.stderr withobjectsthatgetinputfromandsendoutputtotheShellwindow. Theoriginalvaluesstoredinsys.__stdin__,sys.__stdout__,and sys.__stderr__arenottouched,butmaybeNone. Sendingprintoutputfromoneprocesstoatextwidgetinanotheris slowerthanprintingtoasystemterminalinthesameprocess. Thishasthemosteffectwhenprintingmultiplearguments,asthestring foreachargument,eachseparator,thenewlinearesentseparately. Fordevelopment,thisisusuallynotaproblem,butifonewantsto printfasterinIDLE,formatandjointogethereverythingonewants displayedtogetherandthenprintasinglestring.Bothformatstrings andstr.join()canhelpcombinefieldsandlines. IDLE’sstandardstreamreplacementsarenotinheritedbysubprocesses createdintheexecutionprocess,whetherdirectlybyusercodeorby modulessuchasmultiprocessing.Ifsuchsubprocessuseinputfrom sys.stdinorprintorwritetosys.stdoutorsys.stderr, IDLEshouldbestartedinacommandlinewindow.(OnWindows, usepythonorpyratherthanpythonworpyw.) Thesecondarysubprocess willthenbeattachedtothatwindowforinputandoutput. Ifsysisresetbyusercode,suchaswithimportlib.reload(sys), IDLE’schangesarelostandinputfromthekeyboardandoutputtothescreen willnotworkcorrectly. WhenShellhasthefocus,itcontrolsthekeyboardandscreen.Thisis normallytransparent,butfunctionsthatdirectlyaccessthekeyboard andscreenwillnotwork.Theseincludesystem-specificfunctionsthat determinewhetherakeyhasbeenpressedandifso,which. TheIDLEcoderunningintheexecutionprocessaddsframestothecallstack thatwouldnotbethereotherwise.IDLEwrapssys.getrecursionlimitand sys.setrecursionlimittoreducetheeffectoftheadditionalstack frames. WhenusercoderaisesSystemExiteitherdirectlyorbycallingsys.exit, IDLEreturnstoaShellpromptinsteadofexiting. UseroutputinShell¶ Whenaprogramoutputstext,theresultisdeterminedbythe correspondingoutputdevice.WhenIDLEexecutesusercode,sys.stdout andsys.stderrareconnectedtothedisplayareaofIDLE’sShell.Someof itsfeaturesareinheritedfromtheunderlyingTkTextwidget.Others areprogrammedadditions.Whereitmatters,Shellisdesignedfordevelopment ratherthanproductionruns. Forinstance,Shellneverthrowsawayoutput.Aprogramthatsendsunlimited outputtoShellwilleventuallyfillmemory,resultinginamemoryerror. Incontrast,somesystemtextwindowsonlykeepthelastnlinesofoutput. AWindowsconsole,forinstance,keepsauser-settable1to9999lines, with300thedefault. ATkTextwidget,andhenceIDLE’sShell,displayscharacters(codepoints)in theBMP(BasicMultilingualPlane)subsetofUnicode.Whichcharactersare displayedwithaproperglyphandwhichwithareplacementboxdependsonthe operatingsystemandinstalledfonts.Tabcharacterscausethefollowingtext tobeginafterthenexttabstop.(Theyoccurevery8‘characters’).Newline characterscausefollowingtexttoappearonanewline.Othercontrol charactersareignoredordisplayedasaspace,box,orsomethingelse, dependingontheoperatingsystemandfont.(Movingthetextcursorthrough suchoutputwitharrowkeysmayexhibitsomesurprisingspacingbehavior.) >>>s='a\tb\a\bc\nd'#Enter22chars. >>>len(s) 14 >>>s#Displayrepr(s) 'a\tb\x07\x08c\nd' >>>print(s,end='')#Displaysasis. #ResultvariesbyOSandfont.Tryit. Thereprfunctionisusedforinteractiveechoofexpression values.Itreturnsanalteredversionoftheinputstringinwhich controlcodes,someBMPcodepoints,andallnon-BMPcodepointsare replacedwithescapecodes.Asdemonstratedabove,itallowsoneto identifythecharactersinastring,regardlessofhowtheyaredisplayed. Normalanderroroutputaregenerallykeptseparate(onseparatelines) fromcodeinputandeachother.Theyeachgetdifferenthighlightcolors. ForSyntaxErrortracebacks,thenormal‘^’markingwheretheerrorwas detectedisreplacedbycoloringthetextwithanerrorhighlight. Whencoderunfromafilecausesotherexceptions,onemayrightclick onatracebacklinetojumptothecorrespondinglineinanIDLEeditor. Thefilewillbeopenedifnecessary. Shellhasaspecialfacilityforsqueezingoutputlinesdowntoa ‘Squeezedtext’label.Thisisdoneautomatically foroutputoverNlines(N=50bydefault). NcanbechangedinthePyShellsectionoftheGeneral pageoftheSettingsdialog.Outputwithfewerlinescanbesqueezedby rightclickingontheoutput.Thiscanbeusefullineslongenoughtoslow downscrolling. Squeezedoutputisexpandedinplacebydouble-clickingthelabel. Itcanalsobesenttotheclipboardoraseparateviewwindowby right-clickingthelabel. Developingtkinterapplications¶ IDLEisintentionallydifferentfromstandardPythoninorderto facilitatedevelopmentoftkinterprograms.Enterimporttkinterastk; root=tk.Tk()instandardPythonandnothingappears.Enterthesame inIDLEandatkwindowappears.InstandardPython,onemustalsoenter root.update()toseethewindow.IDLEdoestheequivalentinthe background,about20timesasecond,whichisaboutevery50milliseconds. Nextenterb=tk.Button(root,text='button');b.pack().Again, nothingvisiblychangesinstandardPythonuntiloneentersroot.update(). Mosttkinterprogramsrunroot.mainloop(),whichusuallydoesnot returnuntilthetkappisdestroyed.Iftheprogramisrunwith python-iorfromanIDLEeditor,a>>>shellpromptdoesnot appearuntilmainloop()returns,atwhichtimethereisnothingleft tointeractwith. WhenrunningatkinterprogramfromanIDLEeditor,onecancommentout themainloopcall.Onethengetsashellpromptimmediatelyandcan interactwiththeliveapplication.Onejusthastorememberto re-enablethemainloopcallwhenrunninginstandardPython. Runningwithoutasubprocess¶ Bydefault,IDLEexecutesusercodeinaseparatesubprocessviaasocket, whichusestheinternalloopbackinterface.Thisconnectionisnot externallyvisibleandnodataissenttoorreceivedfromtheinternet. Iffirewallsoftwarecomplainsanyway,youcanignoreit. Iftheattempttomakethesocketconnectionfails,Idlewillnotifyyou. Suchfailuresaresometimestransient,butifpersistent,theproblem maybeeitherafirewallblockingtheconnectionormisconfigurationof aparticularsystem.Untiltheproblemisfixed,onecanrunIdlewith the-ncommandlineswitch. IfIDLEisstartedwiththe-ncommandlineswitchitwillrunina singleprocessandwillnotcreatethesubprocesswhichrunstheRPC Pythonexecutionserver.ThiscanbeusefulifPythoncannotcreate thesubprocessortheRPCsocketinterfaceonyourplatform.However, inthismodeusercodeisnotisolatedfromIDLEitself.Also,the environmentisnotrestartedwhenRun/RunModule(F5)isselected.If yourcodehasbeenmodified,youmustreload()theaffectedmodulesand re-importanyspecificitems(e.g.fromfooimportbaz)ifthechanges aretotakeeffect.Forthesereasons,itispreferabletorunIDLE withthedefaultsubprocessifatallpossible. Deprecatedsinceversion3.4. HelpandPreferences¶ Helpsources¶ Helpmenuentry“IDLEHelp”displaysaformattedhtmlversionofthe IDLEchapteroftheLibraryReference.Theresult,inaread-only tkintertextwindow,isclosetowhatoneseesinawebbrowser. Navigatethroughthetextwithamousewheel, thescrollbar,orupanddownarrowkeyshelddown. OrclicktheTOC(TableofContents)buttonandselectasection headerintheopenedbox. Helpmenuentry“PythonDocs”openstheextensivesourcesofhelp, includingtutorials,availableatdocs.python.org/x.y,where‘x.y’ isthecurrentlyrunningPythonversion.Ifyoursystem hasanoff-linecopyofthedocs(thismaybeaninstallationoption), thatwillbeopenedinstead. SelectedURLscanbeaddedorremovedfromthehelpmenuatanytimeusingthe GeneraltaboftheConfigureIDLEdialog. Settingpreferences¶ Thefontpreferences,highlighting,keys,andgeneralpreferencescanbe changedviaConfigureIDLEontheOptionmenu. Non-defaultusersettingsaresavedina.idlercdirectoryintheuser’s homedirectory.Problemscausedbybaduserconfigurationfilesaresolved byeditingordeletingoneormoreofthefilesin.idlerc. OntheFonttab,seethetextsamplefortheeffectoffontfaceandsize onmultiplecharactersinmultiplelanguages.Editthesampletoadd othercharactersofpersonalinterest.Usethesampletoselect monospacedfonts.IfparticularcharactershaveproblemsinShelloran editor,addthemtothetopofthesampleandtrychangingfirstsize andthenfont. OntheHighlightsandKeystab,selectabuilt-inorcustomcolortheme andkeyset.Touseanewerbuilt-incolorthemeorkeysetwitholder IDLEs,saveitasanewcustomthemeorkeysetanditwellbeaccessible toolderIDLEs. IDLEonmacOS¶ UnderSystemPreferences:Dock,onecanset“Prefertabswhenopening documents”to“Always”.Thissettingisnotcompatiblewiththetk/tkinter GUIframeworkusedbyIDLE,anditbreaksafewIDLEfeatures. Extensions¶ IDLEcontainsanextensionfacility.Preferencesforextensionscanbe changedwiththeExtensionstabofthepreferencesdialog.Seethe beginningofconfig-extensions.defintheidlelibdirectoryforfurther information.Theonlycurrentdefaultextensioniszzdummy,anexample alsousedfortesting. idlelib¶ Sourcecode:Lib/idlelib TheLib/idlelibpackageimplementstheIDLEapplication.Seetherest ofthispageforhowtouseIDLE. Thefilesinidlelibaredescribedinidlelib/README.txt.Accessit eitherinidleliborclickHelp=>AboutIDLEontheIDLEmenu.This filealsomapsIDLEmenuitemstothecodethatimplementstheitem. Exceptforfileslistedunder‘Startup’,theidlelibcodeis‘private’in sensethatfeaturechangescanbebackported(seePEP434). TableofContents IDLE Menus Filemenu(ShellandEditor) Editmenu(ShellandEditor) Formatmenu(Editorwindowonly) Runmenu(Editorwindowonly) Shellmenu(Shellwindowonly) Debugmenu(Shellwindowonly) Optionsmenu(ShellandEditor) Windowmenu(ShellandEditor) Helpmenu(ShellandEditor) Contextmenus EditingandNavigation Editorwindows Keybindings Automaticindentation SearchandReplace Completions Calltips CodeContext Shellwindow Textcolors StartupandCodeExecution Commandlineusage Startupfailure Runningusercode UseroutputinShell Developingtkinterapplications Runningwithoutasubprocess HelpandPreferences Helpsources Settingpreferences IDLEonmacOS Extensions idlelib Previoustopic tkinter.tix—ExtensionwidgetsforTk Nexttopic DevelopmentTools ThisPage ReportaBug ShowSource Navigation index modules| next| previous| Python» 3.10.6Documentation» ThePythonStandardLibrary» GraphicalUserInterfaceswithTk» IDLE |



請為這篇文章評分?