Windows tracing flags windows tracing logfile

The official Windows Driver Kit documentation sources - windows-driver-docs/tracelog-command-syntax.md at staging · MicrosoftDocs/windows-driver-docs
title description keywords topic_type api_name api_type ms.date

Tracelog Command Syntax

Tracelog has commands (or actions) that start, stop, and control a trace session.

Tracelog Command Syntax Driver Development Tools

apiref

Tracelog Command Syntax

NA

04/20/2017

Tracelog Command Syntax

Tracelog has commands (or actions) that start, stop, and control a trace session.

[!NOTE]
To control a trace session you must be a member of the Performance Log Users group or the Administrators group on the computer (Run as administrator).

    tracelog [actions] [options] | [-h | -help | -?] 

Parameters

For information about the Tracelog parameters, see [actions] [options].

[actions]

-addautologger [LoggerName]
Configures the registry entries for an autologger session. An autologger session is the preferred method for tracing the activity of a driver or other trace provider during system boot. You must specify the session GUID using the -sessionguid option. The tracelog -addautologger command takes the same options as the Tracelog -start command.

-capturestate [LoggerName]
Requests all providers enabled to LoggerName to log state information. The keywords enabled help determine the kind of information that is logged.

-disable [LoggerName]
Disables the specified trace providers. When a provider is disabled, it continues to run, but it stops generating trace messages.

The tracelog -stop command disables the trace providers before stopping the session. You do not need to disable providers before stopping a trace session. However, you can use the tracelog -disable command to disable selected providers without stopping a trace session.

Disabling stops the trace provider from sending trace messages to the trace session buffers, but it does not flush the buffers or stop the trace session. Use a tracelog -flush command to flush the buffers and a tracelog -stop or tracelog -x (stop all) command to stop the trace session.

Tracelog uses the EnableTrace function to implement a tracelog -disable command. For more information about this function, see the Microsoft Windows SDK documentation.

-enable [LoggerName]
Enables one or more trace providers for the LoggerName trace session.

When you enable a provider, the provider generates trace messages and sends them to the buffers of a trace session. If the provider is not running (or is not loaded) when you enable it, the system pre-registers the provider, that is, it reserves space for the provider in the ETW registration database and saves the enable command. When the provider starts and actually registers, it receives the saved enable command and begins sending trace messages to the session.

The tracelog -start command enables any providers specified by the optional -guid parameter in the tracelog -start command. You do not need to submit a separate tracelog -enable command.

You can use a tracelog -enable command to add a provider to a running trace session, to change the flags and level for a provider while it is tracing, or to re-enable a provider that you disabled by using a tracelog -disable command.

When using the tracelog -enable command, first submit a tracelog -start command to start the trace session, and then submit the tracelog -enable command to enable the providers.

You can enable a running provider repeatedly without disabling it. (You might do this to change the flags and levels.)

The trace flags and trace level that you specify with the -flag and -level parameters are passed to all trace providers represented by the -guid parameter. To specify different flags and levels for each trace provider, submit a separate tracelog -enable command for each provider, with its own flag and level settings.

If you enable any of the NT Kernel Logger flags (such as -noprocess, -nothread, -fio, or -cm) while a Global Logger trace session is running, the Global Logger session is converted to an NT Kernel Logger trace session. This feature is designed to trace kernel events during the boot process.

-enableex [LoggerName]
Identical to -enable. This option may be removed in future versions of Tracelog.

-enumguid
Enumerates (or lists) providers on the system that are registered with Event Tracing for Windows (ETW). For a description of the Enumguid display, see Tracelog Enumguid Display.

Tracelog uses the EnumerateTraceGuids function to implement a tracelog -enumguid command. For more information about this function, see the Microsoft Windows SDK documentation.

-enumguidex [#guid]
Enumerates (or lists) providers on the system that are registered with Event Tracing for Windows (ETW). For a description of the EnumguidEx display, see Tracelog Enumguid Display.

Tracelog uses the EnumerateTraceGuidsEx function to implement a tracelog -enumguidex command. For more information about this function, see the Microsoft Windows SDK documentation.

-flush [LoggerName]
Flushes the active buffers of the LoggerName trace session. If LoggerName is not specified, Tracelog flushes the buffers of the NT Kernel Logger trace session.

This forced flush is in addition to the flushes that occur automatically whenever a trace message buffer is full and when the trace session stops, and in addition to the flushes that are activated by the flush timer (-ft).

When you flush the buffers of a trace session, the events in the buffers are delivered to the trace log or trace consumer immediately.

Flushing does not disable the trace provider or redirect the trace messages. After the buffers are flushed, the trace provider continues writing events to the buffers.

Tracelog uses the FlushTrace function to implement a tracelog -flush command. For more information about this function, see the Microsoft Windows SDK documentation.

You can use the tracelog -flush command with the -f Logfile option to flush the trace messages that are currently in the buffer to the specified trace log (.etl) file. This parameter is valid only for buffered trace sessions (-buffering); for other trace session types, the -f parameter is ignored.

This flush affects only the current contents of the buffer. It does not redirect future trace messages to the trace log.

-l [-lp]
Lists the properties of all trace sessions running on the computer.

If you pass the -lp option, Tracelog will also list all the providers enabled to each session.

-q [LoggerName] [-lp]
Lists (queries) the properties of the specified trace session. If you do not specify LoggerName, Tracelog queries the NT Kernel Logger trace session.

If you pass the -lp option, Tracelog will also list all the providers enabled to the session.

-remove GlobalLogger
Removes and reinitializes the registry values for a Global Logger trace session. It sets the value of the Start entry to 0 (do not start) and deletes the other registry entries. The tracelog -remove command works only for Global Logger trace sessions. All other session name values are invalid.

The tracelog -remove command is not required. However, if you do not set the value of the Start entry to 0, a Global Logger session starts every time you reboot the system.

If you do not use a tracelog -remove command, the options from the previous session are still in the registry, and they will be used for the new session unless you submit a tracelog -start command with different values for the same options.

-start [LoggerName]
Starts a trace session using the LoggerName that you select to represent the trace session.

Use GlobalLogger as the LoggerName to specify a Global Logger Trace Session. The session starts when you restart the computer.

The LoggerName can be any name that meets Windows naming guidelines, up to 1,024 characters. If the name includes spaces, enclose the name in quotation marks. Tracelog is not case-sensitive.

The default is «NT Kernel Logger». If you omit this parameter, Tracelog starts an NT Kernel Logger trace session and declares an error if you use the -guid parameter to specify a different trace provider.

-stop [LoggerName]
Disables the providers in the specified trace session and then terminates the session.

The tracelog -stop command both disables the trace providers and stops the trace session. A tracelog -disable command only disables the trace providers.

If you start a Boot-Time Global Logger session which traces kernel events, you need to use the command tracelog -stop «NT Kernel Logger» or tracelog -stop GlobalLogger to stop it. When you use either of commands to stop a Global Logger trace session trace session, Tracelog stops the provider, but it does not reset the values of the registry entries. To reset the values of the Global Logger registry entries, use tracelog -remove.

-systemrundown [LoggerName]
Requests the SystemTraceProvider to log rundown events directed at LoggerName session. See Configuring and Starting a SystemTraceProvider Session for information about starting a trace session.

This command is only available on Windows 8 and later versions of Windows.

-timeout value
Specifies the timeout value, in milliseconds (ms), to use when enabling providers with the tracelog -enable command. The default timeout is 0.

If the timeout value is 0, the Tracelog will call each provider’s enable callback and return immediately, without waiting for the callback to complete.

To enable providers synchronously, specify a timeout value. If you specify a timeout value, Tracelog will wait until each provider’s enable callback exits or the timeout expires.

When enabling multiple providers at once, the timeout is applied to each one sequentially.

-update [LoggerName]
The tracelog -update command changes the properties of a trace session while it is running.

In a tracelog -update command, the —guid parameter is valid only when updating a private trace session (-um).To add or remove providers from a standard trace session while the session is running, use the tracelog -enable and tracelog -disable commands.

If you start a trace log session (-f), you can update to a real-time session (-rt), but messages continue to be sent to the trace log in addition to the trace consumer. You cannot eliminate the log from the session by updating. However, before you can add real-time message delivery to a trace log session, you must first use the tracelog -flush command to flush the buffers.

If you start a real-time session (-rt) and then update to a trace log session (-f), new trace messages are no longer sent directly to the trace consumer; they are sent only to the trace log. To add a trace log to a real-time trace session, use both -rt and -f in the tracelog -update command. Before you can add real-time message delivery to a trace log session, you must first use the tracelog -flush command to flush the buffers.

You cannot update a Global Logger trace session.

For a private (user-mode) trace session, you can update only the log file name (-f) and the flush timer value (-ft).

To update the flags and levels, use the tracelog -enable command to re-enable the provider with new flags or levels.

Tracelog uses the ControlTrace function to implement a tracelog -update command. For more information about this function, see the Microsoft Windows SDK documentation.

[options]

-addtotriagedump

[!NOTE]
This option should not be used except when you might need to view events from a kernel dump using the debugger.

Specifies that any active buffers for the session are available to be added to a triage memory dump. Triage dumps are limited in size, and if the session’s buffers cause the dump to exceed its maximum size, the buffers will be left out.

-append
Appends the trace messages to the event trace log (.etl) file specified by the -f parameter. The default is to create a new file.

This parameter is valid only in commands that include -f and do not include -rt or -cir.

-b BufferSize
Specifies the size, in KB, of each buffer allocated for the trace session. The default value is determined by the number of processors, the amount of physical memory, and the operating system in use.

-bt n
Specifies the number (n) of buffers to fill before starting to flush them. This option is available starting in Windows 8.1.

-buffering
Starts a buffered trace session.

In a buffered trace session, the trace messages are retained in the trace buffers. They are not sent to a trace consumer or recorded in a trace log.

-cir MaxFileSize
Specifies circular logging (at end-of-file, record new messages over the oldest messages) in the event trace log (.etl) file. MaxFileSize specifies the maximum size of the file in MB. Without a MaxFileSize value, this parameter is ignored.

The default is sequential logging with no file size limit.

-cm
Enables tracing of registry (Configuration Manager) access. This parameter is valid only for an NT Kernel Logger trace session.

-critsec
Traces critical section events for a process in a private trace session. You can start a critical section process logger on any user-mode process, even one that is not instrumented for tracing.

Use -pids to specify the process. Do not use -guid with -critsec. The system defines a custom GUID (CritSecGuid) for critical section traces. You cannot use -heap and -critsec in the same command.

-dpcisr
Enables tracing of deferred procedure calls (DPCs), interrupt service requests (ISRs), image load events (-img), and context switches in the kernel. This parameter is valid only for an NT Kernel Logger trace session.

This option is supported only in the version of Tracelog included in the Windows Driver Kit for Windows Vista and later versions of the WDK. The –dpcisr option cannot be used with the -eflag option.

Use the -UsePerfCounter parameter with -dpcisr. This parameter, which provides a unique time stamp for each event, is required by Tracerpt, a tool used to format and interpret DPC/ISR events. For information about interpreting and formatting these events, see «Comments», below.

-eflag n [flag…]
Enables kernel events using additional flags for NT Kernel Logger trace sessions, most notably, the flags to enable tracing of DPC, ISR, and context switch events. The -eflag option cannot be used with the –dpcisr option.

-enableproperty n
See the description of EnabledProperties in the EnableParameters struct passed as a parameter to EnableTraceEx2 for descriptions and supported values.

-EventIdFilter {-in|-out} **** n **** id1 id2 …
Specifies an event id filter with n event ids (maximum 64 event ids allowed). This option is available starting in Windows 8.1.

-ExeFilter Executable_file [; Executable_file …]
Specifies the names of executable files to filter. You can specify a list of files. Separate the names of the files using semi-colons. Files not listed are excluded. This option is available starting in Windows 8.1.

-f [LogFile]
Starts a trace log session. LogFile specifies the path (optional) and file name of the event trace log (.etl) file. The default is C:LogFile.etl. To place the file on a remote computer, include the computer name or IP address in the path.

If you use -rt with -f, the trace messages are sent to the consumer and to an event trace log file. You cannot use -rt or -f with -buffering.

-fio
Enables tracing of file I/O events. This parameter is valid only for an NT Kernel Logger trace session.

-flag Flag

[!NOTE]
Flags have been superseded by keywords. Use -matchanykw unless you are enabling a WPP provider.

Specifies the trace flags for the providers in the trace session. The flag value determines which events the trace provider generates.

Flag represents a flag value defined in the trace provider, in decimal or hexadecimal format. The default value is 0. Values from 0x01000000 through 0xFF000000 are reserved for future use.

The meaning of the flag value is defined independently by each trace provider. Typically, flags represent increasingly detailed reporting levels.

The flag value specified in a tracelog -start command applies to all trace providers in the trace session. To set different flags for each trace provider, use tracelog -enable.

-ft FlushTime
Specifies how often, in seconds, the trace message buffers are flushed. The minimum flush time is 1 second. The default value is 0 (no forced flush).

This forced flush is in addition to the flushes that happen automatically whenever a trace message buffer is full and when a trace session stops.

See the tracelog -flush command.

-guid {#GUID | file | *name}
Enables the specified trace providers.

If a file is specified, Tracelog will enable tracing for all the providers specified in the file. The file must be formatted as:

; comment line
guid1;matchanykeyword;level
guid2;matchanykeyword;level

If a provider GUID is specified, the GUID must be preceeded by a number sign (#).

If a provider name is specified, the name must be preceeded by an asterisk (*). The name will then be converted into a GUID using the same algorithm as .NET’s Event Source. This GUID will then be used to enable the provider.

If you omit this parameter, no trace providers will send messages to the trace session. However, after starting the trace session, you can use a tracelog -enable command to enable one or more trace providers for the session.

-gs
Generates a global sequence number for each trace message.

Global sequence numbers are unique for all trace sessions on the computer. By default, there are no sequence numbers.

This parameter is not valid with the NT Kernel Logger trace session.

-heap
Traces heap memory events for a user-mode process. You can start a heap process logger on any user-mode process, even one that is not instrumented for tracing.

Use -pids to specify the process. Do not use -guid with -heap. The system defines a custom GUID (HeapGuid) for heap memory traces. You cannot use -heap and -critsec in the same command.

-hf
Enables tracing of hard page faults (page faults that require disk access to resolve). This parameter is valid only for an NT Kernel Logger trace session.

-hybridshutdown {stop|persist}
Controls hybrid shutdown logger behavior. This option is available starting in Windows 8.

stop will cause the session to stop when the system performs a hybrid shutdown.
persist will cause the session to continue after the system starts up again from a hybrid shutdown.

-img
Enables tracing of image load events. This parameter is valid only for an NT Kernel Logger trace session.

-independent

[!NOTE]
Independent mode should be enabled on every trace session.

Enables independent mode on the trace session. Independent mode allows the session to collect events that other non-independent-mode sessions have dropped. This option is available starting in Windows 8.1.

-kb
Use kilobytes (KB) for log file size. The default is megabytes (MB).

-kd
Redirects the trace messages to KD or Windbg, whichever is attached. This parameter also sets the trace buffer size to 3 KB, the maximum buffer size for the debugger, and ignores any -b parameters in the command.

The debugger must be running when you submit a Tracelog command with -kd. Otherwise, Tracelog stops responding.

For information about displaying trace messages in a kernel debugger, see Comments.

-Lbr *EventName[**+EventName+…]:Filter[,*Filter,…]
Configure LBR tracing on kernel events.

Use -eflag Help for a list of kernel events.

-level n
Specifies the trace level for the providers in the trace session. The level determines which events the trace provider generates.

Level represents a level value in decimal or hexadecimal format. The default value is 0.

The meaning of the level value is defined independently by each trace provider. Typically, the trace level represents the severity of the event (information, warning, or error).

The level value specified in a tracelog -start command applies to all trace providers in the trace session. To set different levels for each trace provider, use tracelog -enable.

-lowcapacity

[!NOTE]
This option should not be used unless necessary to reduce memory costs. Using this option makes each event slower to log.

Uses a single buffer at a time to gather events generated on multiple processors. This option selects the EVENT_TRACE_NO_PER_PROCESSOR_BUFFERING logging mode. For more information, see the Windows SDK.

-ls
Generates a local sequence number for each trace message.

Local sequence numbers are unique within a trace session. By default, there are no sequence numbers.

This parameter is not valid with the NT Kernel Logger trace session.

-max NumberOfBuffers
Specifies the maximum number of buffers that Tracelog allocates for the trace session. The default value is determined by the number of processors, the amount of physical memory, and the operating system in use.

-matchallkw n
Specifies the MatchAllKeyWord bitmask that restricts the category of events the provider writes and is used in conjunction with the -matchanykw option.

This bitmask is optional. If the event’s keyword meets the condition specified in the —matchanykw option, the provider will write the event only if all of the bits in this mask exist in the event’s keyword. This mask is not used if -matchanykw is zero.

Tracelog passes the value n in the MatchAllKeyWord parameter of the EnableTraceEx2 function call. See the Windows SDK for more information.

-matchanykw n
Specifies the MatchAnyKeyword bitmask that determines the category of events the provider writes.

The provider writes the event if any of the event’s keyword bits match any of the bits set in this mask. Tracelog passes the value n in the MatchAnyKeyWord parameter of the EnableTraceEx2 function call. See the Windows SDK for more information.

-min NumberOfBuffers
Specifies the number of buffers initially allocated for storing trace messages. When the buffers are full, Tracelog allocates more buffers until it reaches the maximum. The default value is determined by the number of processors, the amount of physical memory, and the operating system in use.

-newfile MaxFileSize
Creates a new event trace log (.etl) file whenever the existing file reaches MaxFileSize. MaxFileSize specifies the maximum size of each log file in MB. Without a MaxFileSize value, this parameter is ignored.

When using -newfile, you must also use the -f LogFile parameter, and the value of LogFile must be a name that includes the characters %d to indicate a decimal pattern—for example, trace%d.etl. Otherwise, the command fails with ERROR_INVALID_NAME. Windows increments the decimal value in the file name each time it creates a new file.

This parameter is not valid with preallocation (-prealloc), circular logging (-cir), with the NT Kernel Logger session, or for private trace sessions.

-nodisk
Disables tracing of physical disk I/O events. This parameter is valid only for an NT Kernel Logger trace session.

-nonet
Disables tracing of TCP/IP and User Datagram Protocol (UDP) events. This parameter is valid only for an NT Kernel Logger trace session.

-noprocess
Disables tracing of the start and end of each process. This parameter is valid only for an NT Kernel Logger trace session.

-nothread
Disables tracing of the start and end of each thread. This parameter is valid only for an NT Kernel Logger trace session.

-paged
Uses pageable memory for the trace message buffers. By default, event tracing uses nonpageable memory for buffers.

Providers that require nonpageable memory will not be able to log events to a session that uses pageable memory.

-pids #PIDs PID [PID…]
Specifies the user-mode processes in which a heap memory or critical section trace session runs. Valid only with -heap or -critsec.

#PIDs specifies the number of process IDs listed with this parameter. PID represents a process identifier. You can specify up to ten PIDs with this parameter.

List multiple PIDs when the provider runs in more than one process, such as when a single program creates multiple processes.

-PidFilter n pid1 pid2 …
Specifies a Pid filter with n Pids (maximum 8 allowed). This option is available starting in Windows 8.1.

-pf
Enables tracing of all page faults. This parameter is valid only for an NT Kernel Logger trace session.

-PkgIdFilter Package Full Name [ **;**Package Full Name…]
Specifies a package ID filter. You can specify a list of package files. Separate the names of the files using semi-colons.

-PkgAppIdFilter PRAID [**;**PRAID…]
Specifies a package-relative app identifier (PRAID) filter. The PRAID is the unique identifier of the application within the package. You can specify more than one PRAID. Separate the IDs using semi-colons. This option is available for UWP apps starting in Windows 8.1.

-Pmc Ctr1,Ctr2,…:Name+Name+…
Configures performance monitor counter (PMC) sampling on the specified kernel events. This option is available starting in Windows 8.

Use -ProfileSource Help for a list of counters.
Use -eflag Help for a list of kernel events.

-prealloc
Reserves space for the .etl file before starting the session.

This parameter requires -seq or -cir with MaxFileSize. It is not valid with -newfile.

-ProfileSource src
Configure profiling source to use. For list of sources, use the command tracelog -ProfileSource Help. This option is available starting in Windows 8.

This option is only available on Windows 8 and later versions of Windows.

-rt
Starts a real-time trace session. (A trace log session (-f) is the default.)

If you use -rt and -f, the trace messages are sent to the trace consumer and to an event trace log file. You cannot use -rt or -f with -buffering. For more information, see Trace Session.

-secure
Enables tracing in secure mode. This option selects the EVENT_TRACE_SECURE_MODE logging mode. Restricts who can log events to the session to those with TRACELOG_LOG_EVENT permission.

-sessionguid
Specifies the autologger session GUID registry value.

-SetProfInt n **** src

[!IMPORTANT]
Changing the profiling interval is not recommended.

Configure the profiling interval (n) for the specified source, where n is in units of 100ns. The default is 10000 (which is equivalent to 1ms). This option is available starting in Windows 8.

-seq MaxFileSize
Specifies sequential logging (at end-of-file, stop recording events) to the event trace log (.etl) file. MaxFileSize specifies the maximum size of the file in MB. Without a MaxFileSize value, this parameter is ignored.

Sequential logging is the default, but you can use this parameter to set the maximum file size or to use -prealloc. Without this parameter, there is no file size limit.

-sourceguid SourceGuid
Specifies the GUID passed as the SourceId parameter to the EnableTraceEx or EnableTraceEx2 functions. The SourceId identifies the session that enabled the provider.

-stackwalk [Events]
Specifies kernel events to collect stacks on. Use -eflag Help for a list of kernel events. This parameter is valid only for the NT Kernel Logger or system logger trace sessions.

-StackWalkFilter {-in|-out}nid1 id2 …
Specifies an event ID filter with n event IDs (maximum 64 event IDs allowed). This option is available starting in Windows 8.1.

-systemlogger
Logger can receive SystemTraceProvider events. See Configuring and Starting a SystemTraceProvider Session. This option is available starting in Windows 8.

-um
Specifies a private trace session This parameter is required for a private trace session.

-UseCPUCycle
Uses the processor frequency (also called «CPU ticks») to measure the time of each trace message.

This timer provides the highest possible resolution, but it is so sensitive that it is prone to error, especially on power-managed systems and multiprocessor computers. For example, if you specify this timer on computer that has an Arm processor, it might result in out-of-order events. Instead, -UsePerfCounter is recommended for high-resolution tracing.

-UsePerfCounter is the default timer for event tracing.

-UsePerfCounter
Records the value of the high-resolution performance counter clock, rather than lower-resolution system time, with each trace message.

Because the performance counter clock counts in approximately 100-nanosecond units, it provides a unique time stamp for each event.

-UsePerfCounter is the default timer for event tracing.

-UseSystemTime
Records the system time, rather than the high-resolution performance counter clock time, with each trace message. Because the system timer has a resolution of 10 milliseconds (compared to 100 nanoseconds for the performance counter clock), multiple events can have the same system time.

-UsePerfCounter is the default timer for event tracing.

-? | help | -?
Displays usage information.

Comments

The following comments apply to several of the Tracelog commands.

Syntax Errors

Tracelog does not display errors for all incorrect syntax combinations, such as when you try to update a setting that cannot be changed. Instead, it ignores the invalid parts of the command and displays a success message.

System Loggers

Windows uses trace sessions for many purposes, some of which are critical for proper operation. Do not stop any trace sessions that you did not start.

Enumguid

To determine whether a tracelog -start or tracelog -enable command was successful, use a tracelog -enumguid command to determine whether the providers were enabled, and then use a tracelog -l (List) command to examine the properties of the trace session.

Real-time and log sessions

A trace session can be both a real-time trace session and a trace log session. If you include the -rt (real-time) and -f (log session) parameters in the same command, the system sends the buffer contents both to the log and to a trace consumer. However, before you can add real-time message delivery to a trace log session, the buffers must be flushed by using the tracelog -flush command.

If you start a real-time session (-rt) and then update to a log session (-f), any new trace messages are sent only to the log file. To add a log file to a real-time session, use both -rt and -f in the tracelog -update command.

If you start a log session (-f), you can update to a real-time session (-rt), but messages continue to be sent to the log in addition to the trace consumer. You cannot eliminate the log from the session by updating.

To display or save trace messages from a real-time-only session, you can also use a trace consumer, such as Tracefmt, or use TraceView, which is both a trace controller (like Tracelog) and a trace consumer. When using Tracefmt, be sure to include the -rt parameter in the Tracefmt command.

Flags and levels

Most trace providers do not generate any trace messages unless the flag or level is set to a particular value. The providers use flags or levels to control what is being traced. If the event trace log file is empty, review the flags and levels in the trace provider.

To ensure that trace messages are always generated, complete the following steps:

  1. Set the flags parameter to 0xFFFFFFFF to enable all flag settings.

  2. Set the levels parameter to 255 to enable all level settings.

The -eflag parameter

Tracelog has an -eflag (extended flags) parameter that was designed to enable additional flags for the NT Kernel Logger trace session—most notably, the flags to enable tracing of DPC, ISR, and context switch events. Because the tracelog -start command now includes the -dpcisr parameter, use of the -eflag parameter is no longer necessary and is not recommended.

Outdated parameters

In previous versions of Tracelog, the tracelog -start command supported the -rt b parameter combination. This combination has been replaced by the -buffering parameter and it is no longer valid.

The -x parameter has been removed because stopping all trace sessions can cause system instability.

The -disableex parameter has been removed. Use -disable instead.

NT Kernel Logger

To start a trace session with the NT Kernel Logger, omit the session name from the tracelog -start command and do not use the -guid parameter to specify a provider GUID file. «NT Kernel Logger» is the default session name.

If the session name is omitted or is «NT Kernel Logger», the system starts an NT Kernel Logger trace session, even if you use a -guid parameter to specify a GUID other than SystemTraceControlGUID, the control GUID for the NT Kernel Logger trace session. If you specify a different GUID, the system returns an error, («System Logger does not accept application guids»), but still starts an NT Kernel Logger trace session.

By default, when Tracelog starts an NT Kernel Logger trace session, it enables traces of process, thread, physical disk I/O, and TCP/IP events, but you can use the parameters to disable tracing of these events and enable tracing of other events.

DPC/ISR events

Because Tracerpt expects a system performance counter clock time as the time stamp, use the Tracelog -UsePerfCounter parameter when you start the trace session.

Because DPC and ISR events are collected by special instrumentation, they do not appear in the Enabled tracing row of the table that Tracelog displays to confirm a command.

For more information, see Example 15: Measuring DPC/ISR Time.

The key to the many options for configuring a tracing session, known informally
as a logger, is a set of bit flags that are typically experienced in user mode as
the LogFileMode member of an EVENT_TRACE_PROPERTIES
structure. Among the options is that a tracing session may have its buffers in user-mode
memory, but if these are not specified, the tracing session is the kernel’s to start
and manage. For communication to the kernel, nowadays through the
NtTraceControl
function, the session’s properties are repackaged as a
WMI_LOGGER_INFORMATION
structure, still with the
bit flags as a ULONG member named
LogFileMode
. This also is how the kernel presents the properties to itself
for those sessions that it starts from AutoLogger settings
in the registry. This note is concerned solely with this kernel-mode interpretation
of the LogFileMode in the WMI_LOGGER_INFORMATION
and the eventual retention of this LogFileMode as the LoggerMode
in the
WMI_LOGGER_CONTEXT
.

Most of the log file modes are documented by Microsoft as
Logging
Mode Constants and are defined as macros in EVNTRACE.H. Not all were documented
immediately. For a few, Microsoft’s names are known only from the NTWMI.H header
which Microsoft published in the Enterprise edition of the Windows Driver Kit (WDK)
for Windows 10 version 1511.

In the following list of log file modes, the versions are those for which the
flag is known to have some explicit recognition by the kernel, even if only to reject
it as invalid. Where versions are not shown, the flag is not known to the kernel
but may instead be vital to the separate NTDLL implementation that lets user-mode
processes do their own event tracing.

Value Name Versions Remarks
0x00000001 EVENT_TRACE_FILE_MODE_SEQUENTIAL 5.0 and higher defined in DDK for Windows 2000;
documented by January 2001
0x00000002 EVENT_TRACE_FILE_MODE_CIRCULAR 5.0 and higher defined in DDK for Windows 2000;
documented by January 2001
0x00000004 EVENT_TRACE_FILE_MODE_APPEND 5.1 and higher defined in DDK for Windows XP;
documented by January 2001
0x00000008 EVENT_TRACE_FILE_MODE_NEWFILE 5.1 and higher defined in DDK for Windows XP;
documented by January 2003
0x00000010 EVENT_TRACE_USE_MS_FLUSH_TIMER 6.1 and higher defined in Enterprise WDK for 1511
0x00000020 EVENT_TRACE_FILE_MODE_PREALLOCATE 6.0 and higher defined in DDK for Windows XP;
documented by January 2003
0x00000040 EVENT_TRACE_NONSTOPPABLE_MODE 6.0 and higher defined in WDK for Windows Vista
0x00000080 EVENT_TRACE_SECURE_MODE 6.0 and higher defined in WDK for Windows Vista
0x00000100 EVENT_TRACE_REAL_TIME_MODE 5.0 and higher defined in DDK for Windows 2000;
documented by January 2001
0x00000200 EVENT_TRACE_DELAY_OPEN_FILE_MODE 5.0 and higher defined in DDK for Windows 2000;
documented by January 2001
0x00000400 EVENT_TRACE_BUFFERING_MODE 6.0 and higher defined in DDK for Windows 2000;
documented by January 2001
0x00000800 EVENT_TRACE_PRIVATE_LOGGER_MODE   defined in DDK for Windows 2000;
documented by January 2001
0x00001000 EVENT_TRACE_ADD_HEADER_MODE 6.0 only defined in DDK for Windows 2000;
documented by January 2001
0x00002000 EVENT_TRACE_USE_KBYTES_FOR_SIZE 6.0 and higher defined in WDK for Windows Vista
0x00004000 EVENT_TRACE_USE_GLOBAL_SEQUENCE 5.1 and higher defined in DDK for Windows XP;
documented by January 2001
0x00008000 EVENT_TRACE_USE_LOCAL_SEQUENCE 5.1 and higher defined in DDK for Windows XP;
documented by January 2001
0x00010000 EVENT_TRACE_RELOG_MODE 6.2 and higher defined in DDK for Windows XP;
documented by January 2003
0x00020000 EVENT_TRACE_PRIVATE_IN_PROC   defined in WDK for Windows Vista
0x00040000 EVENT_TRACE_BUFFER_INTERFACE_MODE 6.1 and higher defined in Enterprise WDK for 1511
0x00080000 EVENT_TRACE_KD_FILTER_MODE 6.0 and higher defined in Enterprise WDK for 1511
0x00100000 EVENT_TRACE_MODE_RESERVED 6.0 only defined in WDK for Windows Vista
EVENT_TRACE_REALTIME_RELOG_MODE   defined in Enterprise WDK for 1511
0x00200000 EVENT_TRACE_LOST_EVENTS_DEBUG_MODE 6.2 and higher defined in Enterprise WDK for 1511
0x00400000 EVENT_TRACE_STOP_ON_HYBRID_SHUTDOWN 6.2 and higher defined in WDK for Windows 8
0x00800000 EVENT_TRACE_PERSIST_ON_HYBRID_SHUTDOWN 6.2 and higher defined in WDK for Windows 8
0x01000000 EVENT_TRACE_USE_PAGED_MEMORY 6.0 and higher defined in DDK for Windows XP;
documented by January 2003
0x02000000 EVENT_TRACE_SYSTEM_LOGGER_MODE 6.2 and higher defined in WDK for Windows 8
0x04000000 EVENT_TRACE_COMPRESSED_MODE 6.2 and higher defined in WDK for 1607
0x08000000 EVENT_TRACE_INDEPENDENT_SESSION_MODE 6.3 and higher defined in WDK for Windows 8.1
0x10000000 EVENT_TRACE_NO_PER_PROCESSOR_BUFFERING 6.1 and higher defined in WDK for Windows 7
0x20000000 EVENT_TRACE_BLOCKING_MODE   defined in Enterprise WDK for 1511
0x40000000 apparently unused    
0x80000000 EVENT_TRACE_ADDTO_TRIAGE_DUMP 6.2 and higher defined in WDK for Windows 8

Validation

Very many of the options are incompatible with other LogFileMode
flags and in some cases with other WMI_LOGGER_INFORMATION
members. By incompatible is here meant that the combination prevents the tracing
session from starting: NtTraceControl fails, returning
STATUS_INVALID_PARAMETER.

The table for each flag shows the constraints that apply if the flag is set when
trying to start a tracing session. These constraints are what the programmer (or
the user who configures AutoLogger settings) would need
to know if thinking to use the flag. Note that many of these constraints were not
enforced immediately that the flag was defined and many seem never to have been
formally documented.

Less easily tabulated are the many requirements and inconsistencies that do not
prevent a tracing session from starting but are instead corrected silently. When
one flag requires another, the natural resolution of the other’s absence is to proceed
as if the other had been set. The one is said (below) to imply the other. Where
two flags are inconsistent, a resolution that stops short of treating them as incompatible
is to accept one but proceed as if the other had been clear. The one is said to
override the other. The terminology is in flux and perhaps never will be sorted
out: if you don’t like it, please consider that Microsoft, who designed this as
part of a product that makes money, is not known to have ever published any serious
attempt.

EVENT_TRACE_FILE_MODE_SEQUENTIAL

Versions Constraints
5.0 and higher invalid with EVENT_TRACE_FILE_MODE_CIRCULAR
6.0 and higher invalid with EVENT_TRACE_BUFFERING_MODE

In version 6.0 and higher, EVENT_TRACE_FILE_MODE_SEQUENTIAL
is implied if either EVENT_TRACE_FILE_MODE_APPEND
or EVENT_TRACE_FILE_MODE_NEWFILE is set.

EVENT_TRACE_FILE_MODE_CIRCULAR

Versions Constraints Side-Effects
5.0 and higher invalid with EVENT_TRACE_FILE_MODE_SEQUENTIAL  
5.1 and higher invalid with EVENT_TRACE_FILE_MODE_APPEND;

invalid with EVENT_TRACE_FILE_MODE_NEWFILE
 
6.0 and higher invalid with EVENT_TRACE_BUFFERING_MODE can allow EVENT_TRACE_NONSTOPPABLE_MODE
6.2 and higher requires MaximumFileSize  

Not only are EVENT_TRACE_FILE_MODE_SEQUENTIAL and
EVENT_TRACE_FILE_MODE_CIRCULAR opposed in all versions,
but the former is a sort of default. In version 6.0 and higher, to omit
EVENT_TRACE_FILE_MODE_CIRCULAR is in effect to set
EVENT_TRACE_FILE_MODE_SEQUENTIAL unless both
EVENT_TRACE_FILE_MODE_APPEND and
EVENT_TRACE_FILE_MODE_NEWFILE are also omitted.

Also starting with version 6.0, setting EVENT_TRACE_FILE_MODE_CIRCULAR
is one way to allow EVENT_TRACE_NONSTOPPABLE_MODE
for an AutoLogger session.

EVENT_TRACE_FILE_MODE_APPEND

Versions Constraints Side-Effects
5.1 and higher invalid with EVENT_TRACE_FILE_MODE_CIRCULAR  
6.0 and higher invalid with EVENT_TRACE_FILE_MODE_PREALLOCATE;

invalid with EVENT_TRACE_BUFFERING_MODE
implies EVENT_TRACE_FILE_MODE_SEQUENTIAL
6.1 and higher invalid with EVENT_TRACE_FILE_MODE_NEWFILE  

EVENT_TRACE_FILE_MODE_NEWFILE

Versions Constraints Side-Effects
5.1 and higher invalid with EVENT_TRACE_FILE_MODE_CIRCULAR;

requires LogFileName;
requires MaximumFileSize
 
5.2 and higher invalid with SystemTraceControlGuid  
6.0 and higher invalid with EVENT_TRACE_FILE_MODE_PREALLOCATE;

invalid with EVENT_TRACE_BUFFERING_MODE;
invalid with 0x00000002 bit in Flags;
invalid with CKCLGuid
implies EVENT_TRACE_FILE_MODE_SEQUENTIAL
6.1 and higher invalid with EVENT_TRACE_FILE_MODE_APPEND  
6.2 and higher invalid with EVENT_TRACE_SYSTEM_LOGGER_MODE  

See that EVENT_TRACE_FILE_MODE_NEWFILE is not permitted
for some particular tracing sessions. These are identified, originally, by the GUID
that is specified in the Guid member of the
Wnode or is inferred from the session’s name. The
SystemTraceControlGuid and CKCLGuid
identify respectively the NT Kernel Logger and the (essentially undocumented) Circular
Kernel Context Logger. That it “should not be used for NT kernel logger sessions”
has been documented since at least 2003 and generalises in version 6.2 to
EVENT_TRACE_SYSTEM_LOGGER_MODE.

Not documented, but perhaps not a surprise, is that EVENT_TRACE_FILE_MODE_NEWFILE
is not permitted for AutoLogger sessions. These are distinguished by the 0x00000002
bit in the Flags.

EVENT_TRACE_FILE_MODE_PREALLOCATE

Versions Constraints
6.0 and higher invalid with EVENT_TRACE_FILE_MODE_APPEND;

invalid with EVENT_TRACE_FILE_MODE_NEWFILE;

requires MaximumFileSize

EVENT_TRACE_NONSTOPPABLE_MODE

Versions Constraints
6.0 and higher requires at least one other LogFileMode bit,
see below;
requires 0x00000002 set in Flags

Microsoft included EVENT_TRACE_NONSTOPPABLE_MODE
in its documentation of Logging Mode Constants some time between 2010 and 2012 as
being “supported on Windows Vista and later.” As the documentation notes, it is
intended for tracing sessions that the kernel starts from AutoLogger
settings in the registry. Enforcement is through the undocumented
Flags bit, which the documented
StartTrace function does not set.

Even for AutoLogger sessions, EVENT_TRACE_NONSTOPPABLE_MODE
requires one of:

  • EVENT_TRACE_FILE_MODE_CIRCULAR;
  • EVENT_TRACE_BUFFERING_MODE;
  • EVENT_TRACE_REAL_TIME_MODE but without a
    LogFileName and, in version 6.0, without
    EVENT_TRACE_DELAY_OPEN_FILE_MODE.

EVENT_TRACE_SECURE_MODE

Nothing invalidates EVENT_TRACE_SECURE_MODE, but
it is implied by EVENT_TRACE_BUFFER_INTERFACE_MODE
in version 6.1 and higher.

EVENT_TRACE_REAL_TIME_MODE

Versions Side-Effects
6.0 and higher can allow EVENT_TRACE_NONSTOPPABLE_MODE

Nothing invalidates EVENT_TRACE_REAL_TIME_MODE,
but it is overridden by EVENT_TRACE_BUFFERING_MODE
in version 6.1 and higher.

In all versions, i.e., 5.0 and higher, EVENT_TRACE_REAL_TIME_MODE
is required if all the following are absent:

  • EVENT_TRACE_DELAY_OPEN_FILE_MODE, in versions
    5.0 to 6.0;
  • EVENT_TRACE_BUFFERING_MODE, in version 6.0 and
    higher;
  • LogFileHandle, in versions 5.0 to 5.2;
  • LogFileName, in version 6.0 and higher.

In version 6.0 and higher, setting EVENT_TRACE_REAL_TIME_MODE
without also providing a LogFileName or setting
EVENT_TRACE_DELAY_OPEN_FILE_MODE allows
EVENT_TRACE_NONSTOPPABLE_MODE for an AutoLogger session
(see above).

EVENT_TRACE_DELAY_OPEN_FILE_MODE

The original ETW implementation allowed that a log file for a tracing session
need not be opened until an event provider actually does write an event for the
tracing session to record. This feature is discontinued for version 5.1 but
EVENT_TRACE_DELAY_OPEN_FILE_MODE continues to be recognised
in the kernel’s code, though without effect in version 6.1 and higher.

Versions Constraints
5.0 only invalid without LogFileName
6.0 only invalid with EVENT_TRACE_NONSTOPPABLE_MODE
if some other LogFileMode bits are clear, see above

In versions 5.0 to 6.0, EVENT_TRACE_DELAY_OPEN_FILE_MODE
is required if all the following are absent:

  • EVENT_TRACE_REAL_TIME_MODE;
  • EVENT_TRACE_BUFFERING_MODE, in version 6.0;
  • LogFileHandle, in versions 5.0 to 5.2;
  • LogFileName, in version 6.0.

EVENT_TRACE_BUFFERING_MODE

Versions Constraints Side-Effects
6.0 and higher invalid with LogFileName;
invalid with EVENT_TRACE_FILE_MODE_SEQUENTIAL;

invalid with EVENT_TRACE_FILE_MODE_CIRCULAR;

invalid with EVENT_TRACE_FILE_MODE_APPEND;
invalid with EVENT_TRACE_FILE_MODE_NEWFILE
can allow EVENT_TRACE_NONSTOPPABLE_MODE
6.1 and higher invalid with EVENT_TRACE_BUFFER_INTERFACE_MODE
overrides EVENT_TRACE_REAL_TIME_MODE;
overrides FlushTimer
6.1 to 6.2   overrides EVENT_TRACE_KD_FILTER_MODE
6.3 and higher   overrides FlushThreshold
1607 and higher   allows EVENT_TRACE_COMPRESSED_MODE

In version 6.0 and higher, EVENT_TRACE_BUFFERING_MODE
is required if all the following are absent:

  • EVENT_TRACE_REAL_TIME_MODE;
  • EVENT_TRACE_DELAY_OPEN_FILE_MODE, in version
    6.0 only;
  • LogFileName.

Also starting with version 6.0, setting EVENT_TRACE_BUFFERING_MODE
allows EVENT_TRACE_NONSTOPPABLE_MODE for an AutoLogger
session.

EVENT_TRACE_USE_GLOBAL_SEQUENCE

Versions Constraints
5.1 and higher invalid with EVENT_TRACE_USE_LOCAL_SEQUENCE

EVENT_TRACE_USE_LOCAL_SEQUENCE

Versions Constraints
5.1 and higher invalid with EVENT_TRACE_USE_GLOBAL_SEQUENCE

EVENT_TRACE_RELOG_MODE

Versions Constraints
6.2 and higher invalid

Early documentation of EVENT_TRACE_RELOG_MODE was
relatively expansive. Nowadays, documentation has it as “reserved for internal use”,
and the whole technical content of what the option exists for is “Logs the event
without including EVENT_TRACE_HEADER.” Once upon a time,
Microsoft continued with

The logger was started to re-log one or more existing log files to a new log file.
Therefore, the variable portion of the re-logged event already has a header from
the old log file.

The option evidently does something useful, just not something that Microsoft
wants programmers writing for themselves. But that’s another story. The option only
ever has been meaningful for user-mode tracing sessions. It’s unknown to the kernel
until version 6.2 makes a point of rejecting it explicitly.

EVENT_TRACE_BUFFER_INTERFACE_MODE

Versions Constraints Side-Effects
6.1 and higher invalid with EVENT_TRACE_BUFFERING_MODE implies EVENT_TRACE_SECURE_MODE

EVENT_TRACE_KD_FILTER_MODE

Versions Side-Effects
6.2 and higher overrides EVENT_TRACE_USE_PAGED_MEMORY

Nothing invalidates EVENT_TRACE_KD_FILTER_MODE.
It is, however, overridden by EVENT_TRACE_BUFFERING_MODE
in versions 6.1 to 6.2. In version 6.2, this override of
EVENT_TRACE_KD_FILTER_MODE
still overrides EVENT_TRACE_USE_PAGED_MEMORY.

EVENT_TRACE_STOP_ON_HYBRID_SHUTDOWN

Versions Constraints
6.2 and higher invalid with EVENT_TRACE_PERSIST_ON_HYBRID_SHUTDOWN

EVENT_TRACE_PERSIST_ON_HYBRID_SHUTDOWN

Versions Constraints
6.2 and higher invalid with EVENT_TRACE_STOP_ON_HYBRID_SHUTDOWN

EVENT_TRACE_USE_PAGED_MEMORY

Versions Constraints
6.2 and higher invalid with EVENT_TRACE_SYSTEM_LOGGER_MODE

A tracing session that has kernel-mode buffers uses non-paged memory by default
but can specify EVENT_TRACE_USE_PAGED_MEMORY. The
buffers are then reserved in paged memory, of course. This is not suitable for kernel-mode
event providers, which are free to write events when access to paged memory is forbidden.
This is in general not a problem if such providers never are enabled for the session,
but to specify EVENT_TRACE_SYSTEM_LOGGER_MODE is to
want from the start that the kernel is an event provider and is ruled out.

Specifying EVENT_TRACE_KD_FILTER_MODE also declares
an intention to receive events when paged memory may be out of bounds, but the resolution
(also in version 6.2 and higher) is just that EVENT_TRACE_USE_PAGED_MEMORY
is overridden.

EVENT_TRACE_SYSTEM_LOGGER_MODE

Versions Constraints
6.2 and higher invalid with EVENT_TRACE_FILE_MODE_NEWFILE;

invalid with EVENT_TRACE_USE_PAGED_MEMORY

EVENT_TRACE_COMPRESSED_MODE

Versions Constraints
6.2 to 1511 invalid
1607 and higher requires EVENT_TRACE_BUFFERING_MODE

Compression of buffers for writing to the log file dates from version 6.2 for
tracing sessions that have user-mode buffers and are managed by NTDLL instead of
the kernel. The compression functionality eventually gets some support for kernel-mode
tracing sessions in the 1607 release of Windows 10. Until then, the kernel explicitly
rejects EVENT_TRACE_COMPRESSED_MODE as invalid.

Данный модуль можно применять во многих случаях. В данном разделе мы не рассмотрим каждый из них. Вместо этого, мы рассмотрим, как именно его можно применять, а также ознакомимся с подмодулем, под названием os.path. В частности, мы расскажем о:

  • os.name
  • os.environ
  • os.chdir()
  • os.getcwd()
  • os.getenv()
  • os.putenv()
  • os.mkdir()
  • os.makedirs()
  • os.remove()
  • os.rename()
  • os.rmdir()
  • os.startfile()
  • os.walk()
  • os.path

Это может выглядеть как большой объем материала, но есть еще минимум десяток других задач, которые модуль os может выполнять. Так что данный раздел можно назвать кратким экскурсом. Для использования любого из методов, упомянутых в данном разделе, вам нужно импортировать модуль os, вот так:

Итак, приступим!

os.name

Модуль os обладает как вызываемыми функциями, так и обычными значениями. В случае с os.name, речь идет только о значениях. При доступе к os.name, вы получите информацию о том, с какой платформой вы работаете. Вам откроются следующие значения: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’, ‘riscos’. Давайте посмотрим на то, что выйдет, если запустить его на Windows 7:

import os

print(os.name) # ответ: nt

Это говорит нам о том, что наш экземпляр Пайтон работает в окне Windows. Как мы об этом узнали? Майкрософт начали называть свою операционную систему NT много лет назад. Например, Windows 7 также носит имя Windows NT 6.1.

os.environ, os.getenv() и os.putenv()

Значение os.environ известно как объект мэппинга (сопоставления), который работает со словарем переменных пользовательской среды. Возможно вы не знали, но каждый раз, когда вы пользуетесь своим компьютером, некоторые переменные среды уже установлены.

Это дает вам полезную информацию, такую как количество процессоров, тип ОЗУ, имя компьютера, и так далее. Посмотрим, что мы сможем узнать о нашем компьютере:

import os

print(os.environ)

Ответ:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

{‘ALLUSERSPROFILE’: ‘C:\ProgramData’,

‘APPDATA’: ‘C:\Users\mike\AppData\Roaming’,

‘CLASSPATH’: ‘.;C:\Program Files\QuickTime\QTSystem\QTJava.zip’,

‘COMMONPROGRAMFILES’: ‘C:\Program Files\Common Files’,

‘COMPUTERNAME’: ‘MIKE-PC’,

‘COMSPEC’: ‘C:\Windows\system32\cmd.exe’,

‘FP_NO_HOST_CHECK’: ‘NO’,

‘HOMEDRIVE’: ‘C:’,

‘HOMEPATH’: ‘\Users\mike’,

‘LOCALAPPDATA’: ‘C:\Users\mike\AppData\Local’,

‘LOGONSERVER’: ‘\\MIKE-PC’,

‘NUMBER_OF_PROCESSORS’: ‘2’,

‘OS’: ‘Windows_NT’,

‘PATHEXT’: ‘.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC’,

‘PROCESSOR_ARCHITECTURE’: ‘x86’,

‘PROCESSOR_IDENTIFIER’: ‘x86 Family 6 Model 15 Stepping 13, GenuineIntel’,

‘PROCESSOR_LEVEL’: ‘6’,

‘PROGRAMDATA’: ‘C:\ProgramData’,

‘PROGRAMFILES’: ‘C:\Program Files’,

‘PSMODULEPATH’: ‘C:\Windows\system32\WindowsPowerShell\v1.0\Modules\’,

‘PUBLIC’: ‘C:\Users\Public’,

‘PYTHONIOENCODING’: ‘cp437’,

‘QTJAVA’: ‘C:\Program Files\QuickTime\QTSystem\QTJava.zip’,

‘SESSIONNAME’: ‘Console’,

‘SYSTEMDRIVE’: ‘C:’,

‘SYSTEMROOT’: ‘C:\Windows’,

‘TEMP’: ‘C:\Users\mike\AppData\Local\Temp’,

‘TMP’: ‘C:\Users\mike\AppData\Local\Temp’,

‘USERDOMAIN’: ‘mike-PC’,

‘USERNAME’: ‘mike’,

‘USERPROFILE’: ‘C:\Users\mike’,

‘VBOX_INSTALL_PATH’: ‘C:\Program Files\Oracle\VirtualBox\’,

‘VS90COMNTOOLS’: ‘C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\’,

‘WINDIR’: ‘C:\Windows’,

‘WINDOWS_TRACING_FLAGS’: ‘3’,

‘WINDOWS_TRACING_LOGFILE’: ‘C:\BVTBin\Tests\installpackage\csilogfile.log’,

‘WINGDB_ACTIVE’: ‘1’,

‘WINGDB_PYTHON’: ‘c:\python27\python.exe’,

‘WINGDB_SPAWNCOOKIE’: ‘rvlxwsGdD7SHYIJm’}

Ваши данные будут отличаться от моих, так как конфигурация компьютера у всех немного отличается, однако вы определенно увидите большое количество совпадений. Как вы могли заметить, это вернуло словарь. Это значит, что вы можете получить доступ к значениям среды, пользуясь обычными словарными методами. Например:

import os

print(os.environ[«TMP»]) # C:\Users\mike\AppData\Local\Temp

Вы также можете использовать функцию os.getenv для доступа к этой переменной:

import os

print(os.getenv(«TMP»)) # C:\Users\mike\AppData\Local\Temp

Полезность использования os.getenv() вместо словаря os.environ заключается в том, что если вы находитесь в положении, когда вам нужно получить доступ к переменной среды, которая не существует, функция getenv попросту ничего не сделает. Если вы попытаетесь сделать то же самое, пользуясь os.environ, вы получите уведомление об ошибке. Давайте попробуем на примере:

import os

print(os.environ[«TMP2»])

Результат выполнения данного скрипта:

Traceback (most recent call last):

    File «<pyshell#1>», line 1, in <module>

        os.environ[«TMP2»]

    File «C:Python27libos.py», line 423, in __getitem__

        return self.data[key.upper()]

KeyError: ‘TMP2’

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

os.chdir() и os.getcwd()

Функция os.chdir позволяет нам вносить изменения в каталоге, который мы в данный момент используем в сессии. Если вам нужно знать, какой путь вы в данный момент используете, для этой нужно вызвать os.getcwd(). Попробуем воспользоваться обоими модулями:

import os

print(os.getcwd()) # C:\Python27

os.chdir(r«C:UsersmikeDocuments»)

print(os.getcwd()) # C:\Users\mike\Documents

Указанный код демонстрирует нам, что мы открыли директорию по умолчанию в Пайтоне, после запуска данного кода в IDLE. После этого мы изменили папки, при помощи os.chdir(). Наконец, мы вызывали os.getcwd() еще раз, чтобы убедиться, что все изменения были выполнены правильно.

os.mkdir() и os.makedirs()

Как вы могли догадаться, эти два метода используются для создания папок. Первая, os.mkdir(), позволяет создать одну папку. Попробуем:

import os

os.mkdir(«test»)

path = r‘C:UsersmikeDocumentspytest’

os.mkdir(path)

Первая строка кода создает папку под названием test в определенном каталоге. Вы можете использовать эти модули в предыдущем разделе, чтобы узнать, где именно вы запустили свой код, на случай, если вы забыли. Во втором примере мы назначили путь к переменной, затем к os.mkdir(). Это позволяет вам создать папку в любой точке вашей системы, где есть доступ. Функция os.makedirs() создает промежуточные папки в пути, если их там нет. В целом, это значит, что вы создали путь, в котором размещены папки. Лично я часто прибегал к данному решению, когда была необходимость создания журнала, с датированной структурой, например ГодМесяцДень. Давайте взглянем на пример:

import os

path = r‘C:UsersmikeDocumentspytest2014219’

os.makedirs(path)

Что произошло? Этот код просто создал кучу папок! Если в вашей системе все еще есть папка pytest, то в ней появится папка 2014, в которой также есть папка, в которой, удивительно, находится еще одна. Попробуйте сами, воспользовавшись рабочим путем в вашей системе.

os.remove() и os.rmdir()

Функции os.remove() и os.rmdir() используются для удаления файлов и каталогов соответственно. Посмотрим на os.remove():

import os

os.remove(«test.txt»)

Этот фрагмент кода пытается удалить файл под названием test.txt из вашего рабочего каталога. Если модуль не может найти файл, должно появиться уведомление о той или иной ошибке. Ошибка также возникнет, если файл уже используется (другими словами закрыт), или у вас нет разрешения для удаления данного файла. Возможно, вы хотите проверить os.unlink, который выполняет ту же функцию. Термин unlink – привычное для Unix название данной процедуры. Взглянем на пример работы os.rmdir():

import os

os.rmdir(«pytest»)

Данный код попытается удалить каталог под названием pytest из каталога, используемого в данный момент в работе. В случае, если это удалось, каталог pytest исчезнет. Ошибка может возникнуть, если каталога с таким названием не существует, если у вас нет разрешения на его удаление, или если каталог не пустой. Вам возможно хочется взглянуть на os.removedirs(), который может удалить пустые вложенные каталоги.

os.rename(src, dst)

Функция os.rename() применяется тогда, когда нужно переименовать файл или папку. Посмотрим на примере:

os.rename(«test.txt», «pytest.txt»)

В этом примере, мы указали os.rename на то, что нужно переименовать файл под названием test.txt на pytest.txt. Это произойдет в каталоге, с которым мы в данный момент работаем. Ошибка может возникнуть в том случае, если вы попытаетесь переименовать несуществующий файл, или если у вас нет доступа к данной операции. Также существует функция os.renames, которая меняет название папки или файла соответственно.

os.startfile()

Метод os.startfile() позволяет нам «запустить» файл в привязанной к нему программе. Другими словами, мы можем открыть файл вместе с привязанной к нему программой, как когда вы открываете файл PDF двойным щелчком, и он открывается в программе Adobe Reader. Попробуем:

import os

os.startfile(r‘C:UsersmikeDocumentslabels.pdf’)

В данном примере мы прошли полный путь к модулю os.startfile, который указывает на открытие файла под названием labels.pdf. На моем компьютере данная функция открывает файл PDF в программе Adobe Reader. Попробуйте открыть файлы PDF, MP3 или фотографии на своем компьютере при помощи данного метода, чтобы увидеть как он работает.

os.walk()

Метод os.walk() дает нам возможность для итерации на корневом уровне пути. Это значит, что мы можем назначить путь к этой функции и получить доступ ко всем её подкаталогам и файлам. Используем одну из папок Пайтон, при помощи которой мы можем проверить данную функцию. Мы используем C:Python27Tools

import os

path = r‘C:Python27Tools’

for root, dirs, files in os.walk(path):

    print(root)

Результат работы:

C:Python27Tools

C:Python27Toolsi18n

C:Python27Toolspynche

C:Python27ToolspyncheX

C:Python27ToolsScripts

C:Python27Toolsversioncheck

C:Python27Toolswebchecker

Мы можем отобразить и весь список каталогов и файлов.

import os

for root, dirs, files in os.walk(path):

    print(root)

    for _dir in dirs:

        print(_dir)

    for _file in files:

        print(_file)

Эта часть кода покажет нам весьма большой объем, так что не будем демонстрировать всю выдачу, вы можете ознакомиться с содержимым сами. Поздравляем, теперь мы готовы к тому, чтобы научиться работать с путями!

os.path

Подмодуль os.path модуля os имеет широкий ряд встроенных преимуществ. Ознакомимся со следующими функциями:

  • basename
  • dirname
  • exists
  • isdir and isfile
  • join
  • split

Это не все функции подмодуля. С ними мы можем ознакомиться позже.

os.path.basename

Функция basename вернет название файла пути. Пример:

import os

os.path.basename(r‘C:Python27ToolspyncheChipViewer.py’)

# ChipViewer.py

Это очень полезная функция, особенно в тех случаях, когда нужно использовать имя файла для наименования того или иного связанного с работой файла, например лог-файл. Такая ситуация возникает часто при работе с файлами данных.

Недорогие и качественные просмотры в Телеграм доступны на сайте ДокторСмм с оптовыми скидками и персональными предложениями. Здесь Вам удастся подобрать, как наиболее привлекательный формат ресурса, так и самую оптимальную скорость поступления, доходящую до 1000 единиц в сутки. При этом Вы можете покупать просмотры, как к конкретному посту, так и ко всей ленте в целом.

os.path.dirname

Функция dirname возвращает только часть каталога пути. Это проще понять, если мы взглянем на пример кода:

import os

print( os.path.dirname(r‘C:Python27ToolspyncheChipViewer.py’) )

# C:\Python27\Tools\pynche

В данном примере мы просто возвращаем путь к каталогу. Это также полезно, когда вам нужно сохранить другие файлы рядом с тем, который вы обрабатываете в данный момент. Как и в случае с лог-файлом, упомянутым выше.

os.path.exists

Функция exists говорит нам, существует ли файл, или нет. Все что вам нужно, это указать ему путь. Взглянем на пример:

import os

os.path.exists(r‘C:Python27ToolspyncheChipViewer.py’) # True

os.path.exists(r‘C:Python27Toolspynchefake.py’) # False

В первом примере, мы указали функции exists настоящий путь, на что она указывает как True. Это говорит о том, что данный путь существует. Во втором примере, мы указали неправильный путь, от чего функция указывает нам на это сообщением False.

os.path.isdir / os.path.isfile

Методы isdir и isfile тесно связаны с методом exists, так как они также тестируют присутствие или отсутствие файлов или папок на тех или иных путях. Однако, isdir проверяет только пути к папкам, а isfile, соответственно, к файлам. Если вам нужно проверить путь, и не важно, папка это или файл, проще будет воспользоваться методом exists. В любом случае, взглянем на пару примеров:

import os

os.path.isfile(r‘C:Python27ToolspyncheChipViewer.py’) # True

os.path.isdir(r‘C:Python27ToolspyncheChipViewer.py’) # False

os.path.isdir(r‘C:Python27Toolspynche’) # True

os.path.isfile(r‘C:Python27Toolspynche’) # False

Уделите особое внимание данным примерам. В первом мы указали путь к файлу и проверили, является ли этот путь в действительности файлом. Затем, во втором примере, мы проделали то же самое, но в контексте папки. Вы можете лично ознакомиться с результатами. После этих двух примеров, мы немного изменили условия, указав путь к папке для обеих функций. Эти примеры наглядно демонстрируют то, как эти функции работают.

os.path.join

Метод join позволяет вам совместить несколько путей при помощи присвоенного разделителя. К примеру, в Windows, в роли разделителя выступает бэкслэш (косая черта, указывающая назад), однако в Linux функция разделителя присвоена косой черте, указывающей вперед (forward slash). Как это работает:

import os

print( os.path.join(r‘C:Python27Toolspynche’, ‘ChipViewer.py’) )

# C:\Python27\Tools\pynche\ChipViewer.py

В данном примере мы совместили путь каталога и файла вместе, для получения рабочего пути. Обратите внимание на то, что метод join не указывает на то, какой результат в итоге вышел.

os.path.split

Метод split разъединяет путь на кортеж, который содержит и файл и каталог. Взглянем на пример:

import os

print( os.path.split(r‘C:Python27ToolspyncheChipViewer.py’) )

# (‘C:\Python27\Tools\pynche’, ‘ChipViewer.py’)

В данном примере показано, что происходит, когда мы указываем путь к файлу. Теперь взглянем на то, что происходит, если в конце пути нет названия файла:

import os

print( os.path.split(r‘C:Python27Toolspynche’) )

# (‘C:Python27Tools’, ‘pynche’)

Как видите, данная функция берет путь и разъединяет его таким образом, что подпапка стала вторым элементом кортежа с остальной частью пути в первом элементе. Напоследок, взглянем на бытовой случай использования split:

import os

dirname, fname = os.path.split(r‘C:Python27ToolspyncheChipViewer.py’)

print(dirname)

# C:\Python27\Tools\pynche

print(fname)

# ChipViewer.py

В данном примере указано, как сделать множественное назначение. Когда вы разъединяете путь, он становится кортежем, состоящим из двух частей. После того, как мы опробовали две переменные с левой части, первый элемент кортежа назначен к первой переменной, а второй элемент к второй переменной соответственно.

Подведем итоги

С данного момента модуль os можно смело назвать старым добрым знакомым. В данном разделе мы научились:

  1. Работать со значениями среды;
  2. Менять каталоги и находить тот, который в данный момент является рабочим;
  3. Создавать и удалять папки и файлы;
  4. Переименовывать папки и файлы;
  5. Открывать файл в соответствующей ему программе;
  6. Работать с путями.

И это не полный список того, что можно делать при помощи модуля os.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

Понравилась статья? Поделить с друзьями:
  • Windows toolkit для windows 10 скачать торрент
  • Windows test signing mode not supported переводчик
  • Windows to the brain на русском
  • Windows terminal скачать без microsoft store
  • Windows to go или стандартная установка windows rufus