[python-win32] Task Scheduler on Windows 7 and pythonw.exe problems

eryksun eryksun at gmail.com
Wed Sep 23 00:42:53 CEST 2015


On 9/22/15, Tim Roberts <timr at probo.com> wrote:
> samilnart . wrote:
>> So when i launch my script on command line using pythonw it works fine
>> but if task scheduler launches it, it instantly crashes without error
>> message. Here is the code: http://pastebin.com/5QfmMrPN . Any help is
>> appreciated.
>
> What user did you use to create your scheduled task?  Is it running as you?

I'll hazard a guess that the script is being run as a regular user, or
as a non-elevated administrator (i.e. without configuring the task to
"run with highest privileges). In this case the netsh command will
fail.

> You might consider using the subprocess module to start your netsh
> commands instead of os.system.  os.system is going to want to create a
> subshell, but processes running in a service (which scheduled tasks do)
> aren't allowed to interact with the desktop.

A console process, such as cmd.exe, doesn't care about creating a
window. That's the job of the console host process, conhost.exe, which
is actually designed to allow running without a window (i.e. the
process creation flag CREATE_NO_WINDOW). I run cmd.exe in session 0
all the time via KpyM SSH. That spawns a "session.exe" console process
in session 0 that defaults to running a cmd shell.

But let's verify that running netsh via cmd actually works when
scheduled as a task that runs in session 0. I'll run as SYSTEM, since
I know the task engine uses session 0 in this case.

    C:\>  schtasks /create /tn firewall_options ^
    More? /ru system /sc once /sd 01/01/1900 /st 00:00 /tr ^
    More? "cmd /c 'netsh firewall /? ^> C:\firewall.txt'"
    WARNING: Task may not run because /ST is earlier than current time.
    SUCCESS: The scheduled task "firewall_options" has successfully
been created.

    C:\>schtasks /run /tn firewall_options
    SUCCESS: Attempted to run the scheduled task "firewall_options".

    C:\>type firewall.txt

    The following commands are available:

    Commands in this context:
    ?              - Displays a list of commands.
    add            - Adds firewall configuration.
    delete         - Deletes firewall configuration.
    dump           - Displays a configuration script.
    help           - Displays a list of commands.
    set            - Sets firewall configuration.
    show           - Shows firewall configuration.

    To view help for a command, type the command, followed by a space, and then
     type ?.

It works!

The script could redirect cmd's stdout and stderr to a log file, as I
did with stdout in the above example. For example:

    os.system(r'"netsh advfirewall set currentprofile state on >
"%TEMP%\netsh.log" 2>&1"')


More information about the python-win32 mailing list