一天一个C Run-Time Library 函数 (7) asctime(时间函数)

本文详细介绍了C语言中的asctime函数,包括其作用、参数、返回值及使用示例,并对比了不同编译器下的实现差异。
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="ProgId" content="Word.Document"> <meta name="Generator" content="Microsoft Word 12"> <meta name="Originator" content="Microsoft Word 12"> <link rel="File-List" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_filelist.xml"> <link rel="themeData" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_themedata.thmx"> <link rel="colorSchemeMapping" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_colorschememapping.xml"> <!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:TrackMoves/> <w:TrackFormatting/> <w:PunctuationKerning/> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:DoNotPromoteQF/> <w:LidThemeOther>EN-US</w:LidThemeOther> <w:LidThemeAsian>ZH-CN</w:LidThemeAsian> <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript> <w:Compatibility> <w:SpaceForUL/> <w:BalanceSingleByteDoubleByteWidth/> <w:DoNotLeaveBackslashAlone/> <w:ULTrailSpace/> <w:DoNotExpandShiftReturn/> <w:AdjustLineHeightInTable/> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:SplitPgBreakAndParaMark/> <w:DontVertAlignCellWithSp/> <w:DontBreakConstrainedForcedTables/> <w:DontVertAlignInTxbx/> <w:Word11KerningPairs/> <w:CachedColBalance/> <w:UseFELayout/> </w:Compatibility> <m:mathPr> <m:mathFont m:val="Cambria Math"/> <m:brkBin m:val="before"/> <m:brkBinSub m:val="&#45;-"/> <m:smallFrac m:val="off"/> <m:dispDef/> <m:lMargin m:val="0"/> <m:rMargin m:val="0"/> <m:defJc m:val="centerGroup"/> <m:wrapIndent m:val="1440"/> <m:intLim m:val="subSup"/> <m:naryLim m:val="undOvr"/> </m:mathPr></w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" DefUnhideWhenUsed="true" DefSemiHidden="true" DefQFormat="false" DefPriority="99" LatentStyleCount="267"> <w:LsdException Locked="false" Priority="0" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Normal"/> <w:LsdException Locked="false" Priority="9" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="heading 1"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 2"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 3"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 4"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 5"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 6"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 7"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 8"/> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 9"/> <w:LsdException Locked="false" Priority="39" Name="toc 1"/> <w:LsdException Locked="false" Priority="39" Name="toc 2"/> <w:LsdException Locked="false" Priority="39" Name="toc 3"/> <w:LsdException Locked="false" Priority="39" Name="toc 4"/> <w:LsdException Locked="false" Priority="39" Name="toc 5"/> <w:LsdException Locked="false" Priority="39" Name="toc 6"/> <w:LsdException Locked="false" Priority="39" Name="toc 7"/> <w:LsdException Locked="false" Priority="39" Name="toc 8"/> <w:LsdException Locked="false" Priority="39" Name="toc 9"/> <w:LsdException Locked="false" Priority="35" QFormat="true" Name="caption"/> <w:LsdException Locked="false" Priority="10" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Title"/> <w:LsdException Locked="false" Priority="1" Name="Default Paragraph Font"/> <w:LsdException Locked="false" Priority="11" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Subtitle"/> <w:LsdException Locked="false" Priority="22" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Strong"/> <w:LsdException Locked="false" Priority="20" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Emphasis"/> <w:LsdException Locked="false" Priority="59" SemiHidden="false" UnhideWhenUsed="false" Name="Table Grid"/> <w:LsdException Locked="false" UnhideWhenUsed="false" Name="Placeholder Text"/> <w:LsdException Locked="false" Priority="1" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="No Spacing"/> <w:LsdException Locked="false" Priority="60" SemiHidden="false" UnhideWhenUsed="false" Name="Light Shading"/> <w:LsdException Locked="false" Priority="61" SemiHidden="false" UnhideWhenUsed="false" Name="Light List"/> <w:LsdException Locked="false" Priority="62" SemiHidden="false" UnhideWhenUsed="false" Name="Light Grid"/> <w:LsdException Locked="false" Priority="63" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 1"/> <w:LsdException Locked="false" Priority="64" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 2"/> <w:LsdException Locked="false" Priority="65" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 1"/> <w:LsdException Locked="false" Priority="66" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 2"/> <w:LsdException Locked="false" Priority="67" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 1"/> <w:LsdException Locked="false" Priority="68" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 2"/> <w:LsdException Locked="false" Priority="69" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 3"/> <w:LsdException Locked="false" Priority="70" SemiHidden="false" UnhideWhenUsed="false" Name="Dark List"/> <w:LsdException Locked="false" Priority="71" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Shading"/> <w:LsdException Locked="false" Priority="72" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful List"/> <w:LsdException Locked="false" Priority="73" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Grid"/> <w:LsdException Locked="false" Priority="60" SemiHidden="false" UnhideWhenUsed="false" Name="Light Shading Accent 1"/> <w:LsdException Locked="false" Priority="61" SemiHidden="false" UnhideWhenUsed="false" Name="Light List Accent 1"/> <w:LsdException Locked="false" Priority="62" SemiHidden="false" UnhideWhenUsed="false" Name="Light Grid Accent 1"/> <w:LsdException Locked="false" Priority="63" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1"/> <w:LsdException Locked="false" Priority="64" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1"/> <w:LsdException Locked="false" Priority="65" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 1 Accent 1"/> <w:LsdException Locked="false" UnhideWhenUsed="false" Name="Revision"/> <w:LsdException Locked="false" Priority="34" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="List Paragraph"/> <w:LsdException Locked="false" Priority="29" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Quote"/> <w:LsdException Locked="false" Priority="30" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Intense Quote"/> <w:LsdException Locked="false" Priority="66" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 2 Accent 1"/> <w:LsdException Locked="false" Priority="67" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1"/> <w:LsdException Locked="false" Priority="68" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1"/> <w:LsdException Locked="false" Priority="69" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1"/> <w:LsdException Locked="false" Priority="70" SemiHidden="false" UnhideWhenUsed="false" Name="Dark List Accent 1"/> <w:LsdException Locked="false" Priority="71" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Shading Accent 1"/> <w:LsdException Locked="false" Priority="72" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful List Accent 1"/> <w:LsdException Locked="false" Priority="73" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Grid Accent 1"/> <w:LsdException Locked="false" Priority="60" SemiHidden="false" UnhideWhenUsed="false" Name="Light Shading Accent 2"/> <w:LsdException Locked="false" Priority="61" SemiHidden="false" UnhideWhenUsed="false" Name="Light List Accent 2"/> <w:LsdException Locked="false" Priority="62" SemiHidden="false" UnhideWhenUsed="false" Name="Light Grid Accent 2"/> <w:LsdException Locked="false" Priority="63" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2"/> <w:LsdException Locked="false" Priority="64" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2"/> <w:LsdException Locked="false" Priority="65" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 1 Accent 2"/> <w:LsdException Locked="false" Priority="66" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 2 Accent 2"/> <w:LsdException Locked="false" Priority="67" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2"/> <w:LsdException Locked="false" Priority="68" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2"/> <w:LsdException Locked="false" Priority="69" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2"/> <w:LsdException Locked="false" Priority="70" SemiHidden="false" UnhideWhenUsed="false" Name="Dark List Accent 2"/> <w:LsdException Locked="false" Priority="71" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Shading Accent 2"/> <w:LsdException Locked="false" Priority="72" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful List Accent 2"/> <w:LsdException Locked="false" Priority="73" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Grid Accent 2"/> <w:LsdException Locked="false" Priority="60" SemiHidden="false" UnhideWhenUsed="false" Name="Light Shading Accent 3"/> <w:LsdException Locked="false" Priority="61" SemiHidden="false" UnhideWhenUsed="false" Name="Light List Accent 3"/> <w:LsdException Locked="false" Priority="62" SemiHidden="false" UnhideWhenUsed="false" Name="Light Grid Accent 3"/> <w:LsdException Locked="false" Priority="63" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3"/> <w:LsdException Locked="false" Priority="64" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3"/> <w:LsdException Locked="false" Priority="65" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 1 Accent 3"/> <w:LsdException Locked="false" Priority="66" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 2 Accent 3"/> <w:LsdException Locked="false" Priority="67" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3"/> <w:LsdException Locked="false" Priority="68" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3"/> <w:LsdException Locked="false" Priority="69" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3"/> <w:LsdException Locked="false" Priority="70" SemiHidden="false" UnhideWhenUsed="false" Name="Dark List Accent 3"/> <w:LsdException Locked="false" Priority="71" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Shading Accent 3"/> <w:LsdException Locked="false" Priority="72" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful List Accent 3"/> <w:LsdException Locked="false" Priority="73" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Grid Accent 3"/> <w:LsdException Locked="false" Priority="60" SemiHidden="false" UnhideWhenUsed="false" Name="Light Shading Accent 4"/> <w:LsdException Locked="false" Priority="61" SemiHidden="false" UnhideWhenUsed="false" Name="Light List Accent 4"/> <w:LsdException Locked="false" Priority="62" SemiHidden="false" UnhideWhenUsed="false" Name="Light Grid Accent 4"/> <w:LsdException Locked="false" Priority="63" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4"/> <w:LsdException Locked="false" Priority="64" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4"/> <w:LsdException Locked="false" Priority="65" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 1 Accent 4"/> <w:LsdException Locked="false" Priority="66" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 2 Accent 4"/> <w:LsdException Locked="false" Priority="67" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4"/> <w:LsdException Locked="false" Priority="68" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4"/> <w:LsdException Locked="false" Priority="69" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4"/> <w:LsdException Locked="false" Priority="70" SemiHidden="false" UnhideWhenUsed="false" Name="Dark List Accent 4"/> <w:LsdException Locked="false" Priority="71" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Shading Accent 4"/> <w:LsdException Locked="false" Priority="72" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful List Accent 4"/> <w:LsdException Locked="false" Priority="73" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Grid Accent 4"/> <w:LsdException Locked="false" Priority="60" SemiHidden="false" UnhideWhenUsed="false" Name="Light Shading Accent 5"/> <w:LsdException Locked="false" Priority="61" SemiHidden="false" UnhideWhenUsed="false" Name="Light List Accent 5"/> <w:LsdException Locked="false" Priority="62" SemiHidden="false" UnhideWhenUsed="false" Name="Light Grid Accent 5"/> <w:LsdException Locked="false" Priority="63" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5"/> <w:LsdException Locked="false" Priority="64" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5"/> <w:LsdException Locked="false" Priority="65" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 1 Accent 5"/> <w:LsdException Locked="false" Priority="66" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 2 Accent 5"/> <w:LsdException Locked="false" Priority="67" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5"/> <w:LsdException Locked="false" Priority="68" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5"/> <w:LsdException Locked="false" Priority="69" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5"/> <w:LsdException Locked="false" Priority="70" SemiHidden="false" UnhideWhenUsed="false" Name="Dark List Accent 5"/> <w:LsdException Locked="false" Priority="71" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Shading Accent 5"/> <w:LsdException Locked="false" Priority="72" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful List Accent 5"/> <w:LsdException Locked="false" Priority="73" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Grid Accent 5"/> <w:LsdException Locked="false" Priority="60" SemiHidden="false" UnhideWhenUsed="false" Name="Light Shading Accent 6"/> <w:LsdException Locked="false" Priority="61" SemiHidden="false" UnhideWhenUsed="false" Name="Light List Accent 6"/> <w:LsdException Locked="false" Priority="62" SemiHidden="false" UnhideWhenUsed="false" Name="Light Grid Accent 6"/> <w:LsdException Locked="false" Priority="63" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6"/> <w:LsdException Locked="false" Priority="64" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6"/> <w:LsdException Locked="false" Priority="65" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 1 Accent 6"/> <w:LsdException Locked="false" Priority="66" SemiHidden="false" UnhideWhenUsed="false" Name="Medium List 2 Accent 6"/> <w:LsdException Locked="false" Priority="67" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6"/> <w:LsdException Locked="false" Priority="68" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6"/> <w:LsdException Locked="false" Priority="69" SemiHidden="false" UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6"/> <w:LsdException Locked="false" Priority="70" SemiHidden="false" UnhideWhenUsed="false" Name="Dark List Accent 6"/> <w:LsdException Locked="false" Priority="71" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Shading Accent 6"/> <w:LsdException Locked="false" Priority="72" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful List Accent 6"/> <w:LsdException Locked="false" Priority="73" SemiHidden="false" UnhideWhenUsed="false" Name="Colorful Grid Accent 6"/> <w:LsdException Locked="false" Priority="19" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis"/> <w:LsdException Locked="false" Priority="21" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis"/> <w:LsdException Locked="false" Priority="31" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference"/> <w:LsdException Locked="false" Priority="32" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Intense Reference"/> <w:LsdException Locked="false" Priority="33" SemiHidden="false" UnhideWhenUsed="false" QFormat="true" Name="Book Title"/> <w:LsdException Locked="false" Priority="37" Name="Bibliography"/> <w:LsdException Locked="false" Priority="39" QFormat="true" Name="TOC Heading"/> </w:LatentStyles> </xml><![endif]--><style> <!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:0; mso-generic-font-family:roman; mso-font-pitch:variable; mso-font-signature:-1610611985 1107304683 0 0 159 0;} @font-face {font-family:Cambria; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:0; mso-generic-font-family:roman; mso-font-pitch:variable; mso-font-signature:-1610611985 1073741899 0 0 159 0;} @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-1610611985 1073750139 0 0 159 0;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} @font-face {font-family:新宋体; panose-1:2 1 6 9 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:modern; mso-font-pitch:fixed; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@新宋体"; panose-1:2 1 6 9 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:modern; mso-font-pitch:fixed; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-unhide:no; mso-style-qformat:yes; mso-style-parent:""; margin-top:0cm; margin-right:0cm; margin-bottom:10.0pt; margin-left:0cm; line-height:115%; mso-pagination:widow-orphan; font-size:12.0pt; mso-bidi-font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:宋体; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-fareast-language:EN-US; mso-bidi-language:EN-US;} h2 {mso-style-priority:9; mso-style-qformat:yes; mso-style-link:"标题 2 Char"; mso-style-next:正文; margin-top:10.0pt; margin-right:0cm; margin-bottom:0cm; margin-left:0cm; margin-bottom:.0001pt; line-height:115%; mso-pagination:widow-orphan lines-together; page-break-after:avoid; mso-outline-level:2; font-size:14.0pt; mso-bidi-font-size:13.0pt; font-family:"Cambria","serif"; mso-ascii-font-family:Cambria; mso-ascii-theme-font:major-latin; mso-fareast-font-family:宋体; mso-fareast-theme-font:major-fareast; mso-hansi-font-family:Cambria; mso-hansi-theme-font:major-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:major-bidi; color:#4F81BD; mso-themecolor:accent1; mso-fareast-language:EN-US; mso-bidi-language:EN-US;} span.MsoIntenseReference {mso-style-priority:32; mso-style-unhide:no; mso-style-qformat:yes; font-variant:small-caps; color:#C0504D; mso-themecolor:accent2; letter-spacing:.25pt; font-weight:bold; text-decoration:underline; text-underline:single;} span.2Char {mso-style-name:"标题 2 Char"; mso-style-priority:9; mso-style-unhide:no; mso-style-locked:yes; mso-style-link:"标题 2"; mso-ansi-font-size:14.0pt; mso-bidi-font-size:13.0pt; font-family:"Cambria","serif"; mso-ascii-font-family:Cambria; mso-ascii-theme-font:major-latin; mso-fareast-font-family:宋体; mso-fareast-theme-font:major-fareast; mso-hansi-font-family:Cambria; mso-hansi-theme-font:major-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:major-bidi; color:#4F81BD; mso-themecolor:accent1; mso-font-kerning:0pt; mso-fareast-language:EN-US; mso-bidi-language:EN-US; font-weight:bold;} .MsoChpDefault {mso-style-type:export-only; mso-default-props:yes; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} --> </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.5pt; mso-bidi-font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-font-kerning:1.0pt;} </style> <![endif]-->

一天一个C Run-Time Library 函数 (7) asctime(时间函数)

write by 九天雁翎(JTianLing) -- blog.youkuaiyun.com/vagrxie

msdn:

Convert a tm time structure to a character string. These functions are deprecated because more secure versions are available; see asctime_s,

char *asctime(

const struct tm *timeptr

);

测试程序:

#include <stdio.h>

#include <time.h>

int main( void )

{

time_t ltNow = time(NULL);

struct tm* lptmNow = localtime(&ltNow);

const char* lpszNow = asctime(lptmNow);

printf("%s",lpszNow);

return 0;

}

说明:

asctime是非常使用的函数,与time(),localtimegmtimemktime,ctime一起构成了C语言世界的时间概念。C中的格林威治时间体系就是由这几个函数来完成的。time_t类型是用来沟通这些函数的桥梁。说明一下,localtime在转换的时候是根据本地locale来转换的,gmtime就是转换标准的格林威治时间,(似乎从结果上来看就是转换成了伦敦时间)。顺面说一下,以_t结尾的类型定义虽然你在Windows中看到是可能是简单的int型,但是即使这样,作为可移植的程序开发,还是应该用原来的类型定义,这样碰到不同实现的时候不至于会导致错误,比如windows中现在time_t现在默认的就是int64了。

与此类似的类型还有pid_t,win_t

实现:

static _TSCHAR * __cdecl store_dt (

REG1 _TSCHAR *p,

REG2 int val

)

{

*p++ = (_TSCHAR)(_T('0') + val / 10);

*p++ = (_TSCHAR)(_T('0') + val % 10);

return(p);

}

REG2 _TSCHAR *p = buffer;

int day, mon;

int i;

day = tb->tm_wday * 3; /* index to correct day string */

mon = tb->tm_mon * 3; /* index to correct month string */

for (i=0; i < 3; i++,p++) {

*p = *(__dnames + day + i);

*(p+4) = *(__mnames + mon + i);

}

*p = _T(' '); /* blank between day and month */

p += 4;

*p++ = _T(' ');

p = store_dt(p, tb->tm_mday); /* day of the month (1-31) */

*p++ = _T(' ');

p = store_dt(p, tb->tm_hour); /* hours (0-23) */

*p++ = _T(':');

p = store_dt(p, tb->tm_min); /* minutes (0-59) */

*p++ = _T(':');

p = store_dt(p, tb->tm_sec); /* seconds (0-59) */

*p++ = _T(' ');

p = store_dt(p, 19 + (tb->tm_year/100)); /* year (after 1900) */

p = store_dt(p, tb->tm_year%100);

*p++ = _T('/n');

*p = _T('/0');

MS:

这个实现是我此系列开始写以后看的源代码中最有意思的源代码了。所以不惜编程源代码的分析都要讲一讲。

很有意思的代码,淋漓尽致的体现了C语言指针的灵活。

for (i=0; i < 3; i++,p++) {

*p = *(__dnames + day + i);

*(p+4) = *(__mnames + mon + i);

}

通过对月和星期的buf,用这个循环完成的6个字符的拷贝更是很让我欣赏:)

通过val/10的加上’0’asc值的方式完成的默认前置0的赋值也是很有意思的技巧。

*p++ = (_TSCHAR)(_T('0') + val / 10);

*p++ = (_TSCHAR)(_T('0') + val % 10);

gcc:

仅仅通过一个简单的snprintf来实现,这估计也是大部分人的实现方式。。。。我要是真的准备实现这样一个代码也会这样实现。

效率测试:

很想知道到底哪个会赢。。。。不过太晚了。。。。

相关函数:

gmtime, localtime, ctime, time,

个人想法:

除了宽字节版本不能使用之外,其他函数的使用自然没有任何问题。并且函数名完全一致。对于这么古老和标准的函数假如还能出现问题,估计任何做可移植程序的人都会崩溃的。放心用吧。

write by 九天雁翎(JTianLing) -- blog.youkuaiyun.com/vagrxie

Microsoft Windows [版本 10.0.19045.5608] (c) Microsoft Corporation。保留所有权利。 F:\789>BUILD_EXE.PY 正在准备构建环境... 安装依赖... Looking in indexes: https://mirrors.aliyun.com/pypi/simple/ Requirement already satisfied: pandas in d:\python\py3.13\lib\site-packages (2.3.0) Requirement already satisfied: openpyxl in d:\python\py3.13\lib\site-packages (3.1.5) Requirement already satisfied: tabulate in d:\python\py3.13\lib\site-packages (0.9.0) Requirement already satisfied: pyinstaller in d:\python\py3.13\lib\site-packages (6.14.1) Requirement already satisfied: pillow in d:\python\py3.13\lib\site-packages (11.2.1) Collecting tkinterdnd2 Downloading https://mirrors.aliyun.com/pypi/packages/08/c3/e04f004a53c00dc01126b6f998264cef672c6883c36aa4bd65845a8eb4c0/tkinterdnd2-0.4.3-py3-none-any.whl (493 kB) Requirement already satisfied: numpy>=1.26.0 in d:\python\py3.13\lib\site-packages (from pandas) (2.3.1) Requirement already satisfied: python-dateutil>=2.8.2 in d:\python\py3.13\lib\site-packages (from pandas) (2.9.0.post0) Requirement already satisfied: pytz>=2020.1 in d:\python\py3.13\lib\site-packages (from pandas) (2025.2) Requirement already satisfied: tzdata>=2022.7 in d:\python\py3.13\lib\site-packages (from pandas) (2025.2) Requirement already satisfied: et-xmlfile in d:\python\py3.13\lib\site-packages (from openpyxl) (2.0.0) Requirement already satisfied: setuptools>=42.0.0 in d:\python\py3.13\lib\site-packages (from pyinstaller) (80.9.0) Requirement already satisfied: altgraph in d:\python\py3.13\lib\site-packages (from pyinstaller) (0.17.4) Requirement already satisfied: pefile!=2024.8.26,>=2022.5.30 in d:\python\py3.13\lib\site-packages (from pyinstaller) (2023.2.7) Requirement already satisfied: pywin32-ctypes>=0.2.1 in d:\python\py3.13\lib\site-packages (from pyinstaller) (0.2.3) Requirement already satisfied: pyinstaller-hooks-contrib>=2025.4 in d:\python\py3.13\lib\site-packages (from pyinstaller) (2025.5) Requirement already satisfied: packaging>=22.0 in d:\python\py3.13\lib\site-packages (from pyinstaller) (25.0) Requirement already satisfied: six>=1.5 in d:\python\py3.13\lib\site-packages (from python-dateutil>=2.8.2->pandas) (1.17.0) Installing collected packages: tkinterdnd2 Successfully installed tkinterdnd2-0.4.3 应用图标已创建 开始打包... 6173 INFO: PyInstaller: 6.14.1, contrib hooks: 2025.5 6173 INFO: Python: 3.13.3 6209 INFO: Platform: Windows-10-10.0.19045-SP0 6209 INFO: Python environment: D:\python\py3.13 6211 INFO: wrote F:\789\TableToMD.spec 6214 INFO: Removing temporary files and cleaning cache in C:\Users\0\AppData\Local\pyinstaller 6216 INFO: Module search paths (PYTHONPATH): ['F:\\789', 'D:\\python\\py3.13\\python313.zip', 'D:\\python\\py3.13\\DLLs', 'D:\\python\\py3.13\\Lib', 'D:\\python\\py3.13', 'D:\\python\\py3.13\\Lib\\site-packages', 'D:\\python\\py3.13\\Lib\\site-packages\\setuptools\\_vendor', 'F:\\789'] 7096 INFO: Appending 'datas' from .spec 7096 INFO: checking Analysis 7097 INFO: Building Analysis because Analysis-00.toc is non existent 7097 INFO: Running Analysis Analysis-00.toc 7097 INFO: Target bytecode optimization level: 0 7098 INFO: Initializing module dependency graph... 7099 INFO: Initializing module graph hook caches... 7137 INFO: Analyzing modules for base_library.zip ... 8830 INFO: Processing standard module hook 'hook-heapq.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 9191 INFO: Processing standard module hook 'hook-encodings.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 11186 INFO: Processing standard module hook 'hook-pickle.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 12917 INFO: Caching module dependency graph... 12954 INFO: Looking for Python shared library... 12974 INFO: Using Python shared library: D:\python\py3.13\python313.dll 12975 INFO: Analyzing F:\789\table_to_md.py 13040 INFO: Processing standard module hook 'hook-pandas.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 15345 INFO: Processing standard module hook 'hook-platform.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 15455 INFO: Processing standard module hook 'hook-sysconfig.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 15522 INFO: Processing standard module hook 'hook-numpy.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 16434 INFO: Processing standard module hook 'hook-difflib.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 16776 INFO: Processing standard module hook 'hook-multiprocessing.util.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 17001 INFO: Processing standard module hook 'hook-xml.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 19675 INFO: Processing pre-safe-import-module hook 'hook-typing_extensions.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks\\pre_safe_import_module' 19689 INFO: SetuptoolsInfo: initializing cached setuptools info... 24695 INFO: Processing standard module hook 'hook-charset_normalizer.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 25329 INFO: Processing standard module hook 'hook-pytz.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 28322 INFO: Processing standard module hook 'hook-pandas.io.formats.style.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 30856 INFO: Processing standard module hook 'hook-pandas.plotting.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 31746 INFO: Processing standard module hook 'hook-openpyxl.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 31993 INFO: Processing standard module hook 'hook-lxml.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 32622 INFO: Processing standard module hook 'hook-lxml.etree.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 32885 INFO: Processing standard module hook 'hook-xml.etree.cElementTree.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 33332 INFO: Processing standard module hook 'hook-PIL.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 33454 INFO: Processing standard module hook 'hook-PIL.Image.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 34198 INFO: Processing standard module hook 'hook-PIL.ImageFilter.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 35938 INFO: Processing standard module hook 'hook-sqlite3.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 36474 INFO: Processing standard module hook 'hook-pandas.io.clipboard.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 36845 INFO: Processing standard module hook 'hook-dateutil.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 37119 INFO: Processing pre-safe-import-module hook 'hook-six.moves.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks\\pre_safe_import_module' 37549 INFO: Processing standard module hook 'hook-xml.dom.domreg.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 38305 INFO: Processing pre-find-module-path hook 'hook-tkinter.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path' 38309 INFO: TclTkInfo: initializing cached Tcl/Tk info... 38898 INFO: Processing standard module hook 'hook-_tkinter.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 38996 INFO: Processing standard module hook 'hook-tkinterdnd2.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 39036 INFO: Analyzing hidden import 'xlwt' 39037 ERROR: Hidden import 'xlwt' not found 39038 INFO: Processing module hooks (post-graph stage)... 39258 INFO: Processing standard module hook 'hook-lxml.isoschematron.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 39283 WARNING: Hidden import "jinja2" not found! 39592 INFO: Processing standard module hook 'hook-PIL.SpiderImagePlugin.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 39653 INFO: Processing standard module hook 'hook-_tkinter.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks' 39655 INFO: Processing standard module hook 'hook-lxml.objectify.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\_pyinstaller_hooks_contrib\\stdhooks' 39673 INFO: Performing binary vs. data reclassification (1560 entries) 40208 INFO: Looking for ctypes DLLs 40268 INFO: Analyzing run-time hooks ... 40273 INFO: Including run-time hook 'pyi_rth_inspect.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks' 40282 INFO: Including run-time hook 'pyi_rth_pkgutil.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks' 40285 INFO: Including run-time hook 'pyi_rth_multiprocessing.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks' 40287 INFO: Including run-time hook 'pyi_rth__tkinter.py' from 'D:\\python\\py3.13\\Lib\\site-packages\\PyInstaller\\hooks\\rthooks' 40338 INFO: Creating base_library.zip... 40379 INFO: Looking for dynamic libraries 41975 INFO: Extra DLL search directories (AddDllDirectory): ['D:\\python\\py3.13\\Lib\\site-packages\\numpy.libs', 'D:\\python\\py3.13\\Lib\\site-packages\\pandas.libs'] 41975 INFO: Extra DLL search directories (PATH): [] 44927 INFO: Warnings written to F:\789\build\TableToMD\warn-TableToMD.txt 45012 INFO: Graph cross-reference written to F:\789\build\TableToMD\xref-TableToMD.html 45081 INFO: checking PYZ 45082 INFO: Building PYZ because PYZ-00.toc is non existent 45082 INFO: Building PYZ (ZlibArchive) F:\789\build\TableToMD\PYZ-00.pyz 46228 INFO: Building PYZ (ZlibArchive) F:\789\build\TableToMD\PYZ-00.pyz completed successfully. 46332 INFO: checking PKG 46332 INFO: Building PKG because PKG-00.toc is non existent 46333 INFO: Building PKG (CArchive) TableToMD.pkg 56140 INFO: Building PKG (CArchive) TableToMD.pkg completed successfully. 56162 INFO: Bootloader D:\python\py3.13\Lib\site-packages\PyInstaller\bootloader\Windows-64bit-intel\run.exe 56162 INFO: checking EXE 56163 INFO: Building EXE because EXE-00.toc is non existent 56163 INFO: Building EXE from EXE-00.toc 56163 INFO: Copying bootloader EXE to F:\789\dist\TableToMD.exe 56203 INFO: Copying icon to EXE 56210 INFO: Copying 0 resources to EXE 56210 INFO: Embedding manifest in EXE 56217 INFO: Appending PKG archive to EXE 56278 INFO: Fixing EXE headers 56752 INFO: Building EXE from EXE-00.toc completed successfully. 56774 INFO: Build complete! The results are available in: F:\789\dist 构建完成! EXE文件在 dist 目录中 运行 TableToMD.exe 启动程序 为什么启动程序没有应用界面呢?
06-23
<think>根据构建日志,构建过程没有报错,但是运行程序没有界面。这可能是由于以下原因:1.程序以命令行模式运行(可能传递了参数导致直接运行命令行模式)2.程序启动时发生错误但未显示3.打包时遗漏了必要的资源或模块由于程序同时支持命令行和GUI模式,在没有参数的情况下应该启动GUI。但是,如果程序在启动时发生错误,控制台窗口可能会一闪而过,看不到错误信息。我们可以尝试以下步骤来排查:###步骤1:从命令行运行程序在命令提示符中运行生成的EXE文件,这样可以看到任何错误输出:```cmdF:\789\dist\TableToMD.exe```###步骤2:检查打包时是否包含所有依赖构建日志中有一个错误:```39036INFO:Analyzinghiddenimport'xlwt'39037ERROR:Hiddenimport'xlwt'notfound```虽然xlwt不是必需的(因为处理的是xlsx,不是xls),但可能还有其他依赖缺失。###步骤3:添加必要的运行时钩子(hooks)特别是对于tkinter和pandas,可能需要额外的钩子。###步骤4:确保资源文件正确包含我们打包时包含了图标文件,但需要确保在运行时能正确访问。###解决方案####1.从命令行运行以捕获错误如果运行后控制台显示错误,根据错误信息调整。####2.修复缺失的隐藏导入在构建脚本中,我们添加了`--hidden-import`参数,但似乎`xlwt`没有安装。我们可以忽略它,因为我们的程序可能不需要它(除非用户要处理.xls文件)。但为了安全,我们可以安装它:```bashpipinstallxlwt```然后重新构建。####3.添加tkinterdnd2的钩子虽然我们已经在构建脚本中指定了隐藏导入,但可能需要为tkinterdnd2添加特定的钩子。####4.确保图标资源正确访问在代码中,我们使用了条件判断来处理打包后的资源路径:```pythonifhasattr(sys,'_MEIPASS'):icon_path=os.path.join(sys._MEIPASS,'app_icon.ico')else:icon_path="app_icon.ico"```在构建时,我们通过`--add-data=app_icon.ico;.`将图标文件添加到了包中。在运行时,当程序被打包后,`sys._MEIPASS`指向临时解压目录,图标文件应该在那里。####5.添加错误捕获在`main()`函数中添加异常捕获,将错误写入文件或显示消息框。###修改代码以捕获启动错误在`main()`函数中,我们可以添加全局异常捕获:```pythondefmain():try:#...原有的main函数代码...exceptExceptionase:#尝试显示错误消息框,如果tkinter可用的话try:importtkinterastkfromtkinterimportmessageboxroot=tk.Tk()root.withdraw()messagebox.showerror("启动错误",f"程序启动时发生错误:{str(e)}")root.destroy()except:print(f"启动错误:{str(e)}")input("按回车键退出...")sys.exit(1)```###修改构建脚本,添加更多隐藏导入在`build_exe.py`中,添加更多可能需要的隐藏导入:```pythonhidden_imports=['pandas','openpyxl','tkinter','PIL','tkinterdnd2','numpy','xlrd','xlwt','tkinterdnd2.tkinterdnd2',#明确导入tkinterdnd2的子模块'pandas._libs','pandas._libs.tslibs',#pandas的内部库]```###重新构建并测试1.安装xlwt:```bashpipinstallxlwt```2.更新构建脚本中的隐藏导入列表3.重新运行构建脚本###如果问题仍然存在如果仍然没有界面,我们可以尝试强制程序以GUI模式启动,修改代码:在`main()`函数中,在解析命令行参数后,如果没有任何输入参数,强制设置`args.gui=True`:```pythonifnotargs.inputandnotargs.gui:args.gui=True```这样,当没有提供任何输入文件时,总是启动GUI。###完整修改后的main函数```pythondefmain():try:#命令行参数解析parser=argparse.ArgumentParser(description='表格文件转Markdown转换器v2.0',formatter_class=argparse.RawTextHelpFormatter)#...参数定义...args=parser.parse_args()#如果没有输入参数,强制使用GUIifnotargs.input:args.gui=True#如果有命令行参数,使用命令行模式ifargs.inputandnotargs.gui:#...命令行模式...else:#启动GUIroot=tk.Tk()app=TableToMDApp(root)root.mainloop()exceptExceptionase:#错误处理...```###最终建议如果上述方法都不能解决问题,我们可以尝试在程序启动时创建一个日志文件,记录程序执行过程,以便发现错误。在程序开头添加日志初始化:```pythonimportloggingdefsetup_logging():logging.basicConfig(filename='TableToMD.log',level=logging.DEBUG,format='%(asctime)s-%(levelname)s-%(message)s')if__name__=="__main__":setup_logging()try:main()exceptExceptionase:logging.exception("程序崩溃")raise```这样,程序崩溃时会在当前目录生成日志文件。###重新构建后的完整代码由于代码较长,这里只给出修改的关键部分。请将以下修改应用到你的代码中。####修改main函数```pythondefmain():#命令行参数解析parser=argparse.ArgumentParser(description='表格文件转Markdown转换器v2.0',formatter_class=argparse.RawTextHelpFormatter)parser.add_argument('input',nargs='*',help='输入文件路径、目录或通配符模式')parser.add_argument('-o','--output',help='输出目录')parser.add_argument('-r','--recursive',action='store_true',help='递归处理子目录')parser.add_argument('-v','--verbose',action='store_true',help='显示详细输出')parser.add_argument('--version',action='version',version='TableToMDv2.0')parser.add_argument('--gui',action='store_true',help='强制使用图形界面')args=parser.parse_args()#如果没有输入参数,强制使用GUIifnotargs.input:args.gui=True#如果有命令行参数,使用命令行模式ifargs.inputandnotargs.gui:#...命令行模式代码...else:#没有命令行参数或指定了--gui,启动GUIroot=tk.Tk()app=TableToMDApp(root)root.mainloop()```####在程序入口添加日志```pythonimportloggingdefsetup_logging():logging.basicConfig(filename='TableToMD.log',level=logging.DEBUG,format='%(asctime)s-%(levelname)s-%(message)s')if__name__=="__main__":setup_logging()logging.info("程序启动")try:main()exceptExceptionase:logging.exception("程序崩溃")#尝试显示错误消息try:importtkinterastkfromtkinterimportmessageboxroot=tk.Tk()root.withdraw()messagebox.showerror("程序崩溃",f"发生致命错误:{str(e)}")root.destroy()except:print(f"程序崩溃:{str(e)}")sys.exit(1)```###重新构建在修改代码后,重新运行`build_exe.py`。###运行测试运行新生成的EXE,并检查:1.如果程序启动,问题解决。2.如果程序没有启动,检查当前目录下的`TableToMD.log`文件。根据日志文件中的错误信息,进一步调整。###§§相关问题§§:1.如何为PyInstaller打包的程序添加日志功能以方便调试?2.在Windows平台下,如何让PyInstaller打包的程序在崩溃时显示错误信息?3.如何减小PyInstaller打包生成的单文件EXE的体积?4.如何为PyInstaller打包的程序添加版本信息和公司信息?</think>### 解决 EXE 程序无界面问题 您遇到的问题是构建的 EXE 程序运行后没有显示界面。这通常是由于以下几个原因造成的: 1. **控制台模式与 GUI 模式冲突** 2. **运行时依赖缺失** 3. **资源路径处理错误** 4. **Tkinter 初始化问题** 以下是完整的解决方案: #### 修复代码:强制 GUI 模式启动 ```python def main(): # ... [参数解析代码保持不变] ... # 修改启动逻辑 if args.gui or not args.input: # GUI 模式 root = tk.Tk() app = TableToMDApp(root) root.mainloop() else: # 命令行模式 # ... [命令行模式代码保持不变] ... ``` #### 添加详细的启动日志 ```python def main(): try: logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', filename='TableToMD.log', filemode='w' ) logger = logging.getLogger() logger.info("程序启动") logger.info(f"命令行参数: {sys.argv}") logger.info(f"Python 版本: {sys.version}") logger.info(f"操作系统: {sys.platform}") # ... [原有代码] ... except Exception as e: logger.exception("程序启动失败") # 尝试显示错误消息 try: root = tk.Tk() root.withdraw() messagebox.showerror("启动错误", f"程序启动失败: {str(e)}") except: print(f"程序启动失败: {str(e)}") ``` #### 修复资源路径处理 ```python class TableToMDApp: def __init__(self, root=None): # ... def setup_gui(self, root): # ... try: # 改进的资源路径处理 icon_path = None if hasattr(sys, '_MEIPASS'): # 打包环境 base_path = sys._MEIPASS possible_paths = [ os.path.join(base_path, 'app_icon.ico'), os.path.join(base_path, 'resources', 'app_icon.ico'), os.path.join(os.getcwd(), 'app_icon.ico') ] for path in possible_paths: if os.path.exists(path): icon_path = path break else: # 开发环境 icon_path = "app_icon.ico" if icon_path and os.path.exists(icon_path): self.root.iconbitmap(icon_path) logging.info(f"图标加载成功: {icon_path}") else: logging.warning("图标文件未找到") except Exception as e: logging.error(f"图标加载失败: {str(e)}") ``` #### 更新构建脚本 (build_exe.py) ```python def build_executable(): # ... [原有代码] ... # 更新打包参数 params = [ 'table_to_md.py', '--name=TableToMD', '--onefile', '--windowed', # 改为窗口模式,不显示控制台 '--icon=app_icon.ico', '--add-data=app_icon.ico;resources', # 将图标放入resources子目录 '--noconfirm', '--clean', '--runtime-tmpdir=.', # 设置运行时临时目录 '--add-binary=python313.dll;.' # 显式包含Python DLL ] # 添加必要的隐藏导入 hidden_imports = [ 'pandas', 'openpyxl', 'tkinter', 'PIL', 'numpy', 'tkinterdnd2', 'xlrd', 'xlwt', 'pytz', 'dateutil', 'tkinterdnd2.tkinterdnd2', # 显式包含tkinterdnd2子模块 'pandas._libs', # pandas内部库 'scipy' # pandas可能依赖的库 ] for imp in hidden_imports: params.append(f'--hidden-import={imp}') # 添加数据文件 params.append('--add-data=tcl;tcl') params.append('--add-data=tk;tk') # ... [执行打包] ... ``` #### 创建批处理文件测试 ```batch :: RunTest.bat @echo off echo 正在启动 TableToMD.exe... start "" /wait "dist\TableToMD.exe" echo 程序已退出,返回码=%errorlevel% echo 查看日志文件 TableToMD.log 获取详细信息 pause ``` ### 问题原因分析 根据您的构建日志,我发现几个关键问题: 1. **Tkinter 依赖问题**: ``` 38305 INFO: Processing pre-find-module-path hook 'hook-tkinter.py' 38309 INFO: TclTkInfo: initializing cached Tcl/Tk info... ``` 这表明 Tkinter 资源没有正确包含 2. **隐藏导入缺失**: ``` 39036 INFO: Analyzing hidden import 'xlwt' 39037 ERROR: Hidden import 'xlwt' not found 39283 WARNING: Hidden import "jinja2" not found! ``` 3. **资源路径问题**: 图标文件可能没有被正确包含到最终包中 ### 解决方案步骤 #### 1. 安装缺失的依赖 ```bash pip install xlwt jinja2 ``` #### 2. 更新构建脚本 使用上面提供的改进版构建脚本 #### 3. 添加 Tcl/Tk 资源 创建 `hook-tkinter.py` 文件: ```python # hook-tkinter.py from PyInstaller.utils.hooks import collect_data_files # 包含 Tcl/Tk 运行时文件 datas = collect_data_files('tkinter') ``` 在构建命令中添加: ```python params.append('--additional-hooks-dir=.') # 包含当前目录的钩子 ``` #### 4. 重新构建并测试 ```bash python build_exe.py RunTest.bat ``` ### 替代方案:使用 NSIS 创建安装包 如果直接构建的 EXE 仍有问题,可以使用 NSIS 创建完整的安装包: 1. **安装 NSIS**:[nsis.sourceforge.io](https://nsis.sourceforge.io/Download) 2. **创建安装脚本** `TableToMD.nsi`: ```nsis ; TableToMD.nsi !include "MUI2.nsh" ; 基本信息 Name "TableToMD" OutFile "TableToMD_Setup.exe" InstallDir "$PROGRAMFILES\TableToMD" RequestExecutionLevel admin ; 界面设置 !define MUI_ICON "app_icon.ico" !define MUI_UNICON "app_icon.ico" !define MUI_WELCOMEFINISHPAGE_BITMAP "welcome.bmp" !define MUI_UNWELCOMEFINISHPAGE_BITMAP "unwelcome.bmp" ; 页面 !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_PAGE_FINISH !insertmacro MUI_UNPAGE_WELCOME !insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_UNPAGE_FINISH ; 语言 !insertmacro MUI_LANGUAGE "English" Section "Main Application" SetOutPath "$INSTDIR" ; 包含主程序 File "dist\TableToMD.exe" File "app_icon.ico" ; 包含依赖 File /r "tcl" File /r "tk" ; 创建快捷方式 CreateDirectory "$SMPROGRAMS\TableToMD" CreateShortcut "$SMPROGRAMS\TableToMD\TableToMD.lnk" "$INSTDIR\TableToMD.exe" "" "$INSTDIR\app_icon.ico" CreateShortcut "$DESKTOP\TableToMD.lnk" "$INSTDIR\TableToMD.exe" "" "$INSTDIR\app_icon.ico" ; 注册卸载程序 WriteUninstaller "$INSTDIR\Uninstall.exe" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\TableToMD" \ "DisplayName" "TableToMD" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\TableToMD" \ "UninstallString" "$\"$INSTDIR\Uninstall.exe$\"" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\TableToMD" \ "DisplayIcon" "$\"$INSTDIR\app_icon.ico$\"" SectionEnd Section "Uninstall" ; 删除文件 Delete "$INSTDIR\TableToMD.exe" Delete "$INSTDIR\Uninstall.exe" RMDir /r "$INSTDIR\tcl" RMDir /r "$INSTDIR\tk" ; 删除快捷方式 Delete "$DESKTOP\TableToMD.lnk" Delete "$SMPROGRAMS\TableToMD\*.*" RMDir "$SMPROGRAMS\TableToMD" ; 删除注册表项 DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\TableToMD" ; 删除安装目录 RMDir "$INSTDIR" SectionEnd ``` 3. **编译安装包**: ```bash makensis TableToMD.nsi ``` ### 调试技巧 1. **检查日志文件**: 程序会在运行目录创建 `TableToMD.log` 2. **使用 Process Explorer**: 查看进程是否仍在运行但没有显示界面 3. **依赖检查**: 使用 Dependency Walker 检查 EXE 的依赖关系 4. **控制台模式测试**: ```bash dist\TableToMD.exe test.csv -v ``` ### 最终解决方案总结 1. **代码修复**: - 强制 GUI 模式启动逻辑 - 改进资源路径处理 - 添加详细日志记录 2. **构建修复**: - 添加必要的隐藏导入 - 包含 Tcl/Tk 运行时文件 - 使用窗口模式 (`--windowed`) 3. **安装包方案**: - 使用 NSIS 创建完整安装包 - 确保所有依赖正确部署 4. **测试方案**: - 创建测试批处理文件 - 添加详细的日志记录 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值