3

I've been working on a small script that's supposed to run in the background of my computer. I already have the script working and everything except one thing that hours of google searching and hunting have not found the answer to.

The file has a .pyw extension, and when I run it from the command prompt:

pythonw File.pyw

the cmd window will continue on and give me another prompt without launching idle like it would with a regular .py file.

When I double-click the file, the cmd window opens and closes without a problem, just like it's supposed to. This is all perfect for me.

However, I tried to make a small batch file:

cd C:\Users\(my name)\Desktop
pythonw File.pyw

and I stuck that in the startup folder of windows. However, when I restarted my computer to see if it would work, it opened the cmd window, but wouldn't close it. I can't figure out why. I've tried everything I can think of, including sticking the File.pyw directly in the startup folder, and trying to put an exit command right in the batch file like so:

cd C:\Users\(my name)\Desktop
pythonw File.pyw
exit

But, as you can probably guess, that failed. I tried putting the command directly in my code, so right before the end, it had the line

os.system("exit")

but after realizing this wouldn't work, I just took it out. (Important detail: the last line of the code is set to loop it until the program closes. That's why I'm trying to use the pyw extension, so the console can close before the file ends)

Next, I shortened the batch file to only be the one line:

pythonw.exe C:\Users\(my name)\Desktop\File.pyw

but it still won't work. When the batch file is run, I get an open cmd window with the command entered, but it runs like a regular .py file, not closing the cmd window.

Can anyone help me figure out why the console won't close when the command is run from a .batch file, but will when run directly from command prompt?

UPDATE:

the script is meant to add a quick keyboard shortcut to close a task, specifically Google Chrome, when I press '+' twice quickly. Here's a my full code (minus some personal info)

import os
import sys
import pyHook, pythoncom

setting key to be '+' to avoid accidental usage.
def OnKeyBoardEvent(event):
    global prevPlus, escPushed
    if event.Ascii == 43:
        if prevPlus == None:
            prevPlus = event.Time
        else:
            if event.Time - prevPlus <= 1000:
                os.system("taskkill /IM chrome.exe")
                prevPlus = event.Time
            else:
                prevPlus = event.Time
    elif event.Ascii == 27:
        if escPushed == None:
            escPushed = event.Time
        else:
            if event.Time - escPushed <= 1000:
            sys.exit()
            else:
                escPushed = event.Time


getter = pyHook.HookManager()
getter.KeyDown = OnKeyBoardEvent
getter.HookKeyboard()

prevPlus = None
escPushed = None

pythoncom.PumpMessages()

This all works perfectly when I'm running it from pycharm, or from cmd, but when I put it in C:\Users(my name)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup and then try it out, nothing happens. I'm guessing it's because windows runs the file and exits it before anything happens, but I'm really not sure. I just really need a solution that makes it run at startup and take my key input until I shut down.

JustDucky
  • 132
  • 1
  • 10
  • http://serverfault.com/questions/9038/run-a-bat-file-in-a-scheduled-task-without-a-window – Bender Dec 31 '15 at 04:16
  • I tried using a vbs file to send commands, but the console is still staying up. Is there any way of doing the equivalent of double-clicking the file from the command line? – JustDucky Dec 31 '15 at 05:15
  • you can exit , if you are calling your script from batch file http://ss64.com/nt/exit.html – Bender Dec 31 '15 at 05:59
  • Don't use a batch file. Just drop the script or a shortcut to it in the startup folder. Unless your script runs other commands via subprocess or `os.system`, no console window should appear since .pyw scripts run via the non-console program "pythonw.exe". – Eryk Sun Dec 31 '15 at 07:22
  • Running a .py script should not run IDLE. Your system is misconfigured if that happens. The `Python.File` progid is the default association for .py scripts. This executes the script using the template command line `python.exe "%1" %*`. – Eryk Sun Dec 31 '15 at 07:26
  • Sorry, I didn't mean to say that it ran IDLE, I just meant that it entered an idle-like interface, where it would prompt for a python command and execute it line by line. – JustDucky Dec 31 '15 at 20:47
  • You'll have to provide a complete example to reproduce the problem. Otherwise I'd just be wasting my time guessing. – Eryk Sun Dec 31 '15 at 23:38
  • You could make an executable with pyinstaller using the `--noconsole` option. – cdonts Jan 01 '16 at 05:32
  • To prevent creating a console (i.e. an instance of conhost.exe with a window), replace `os.system("taskkill /IM chrome.exe")` with `import subprocess; DETACHED_PROCESS = 0x00000008;` `subprocess.call('taskkill.exe /im chrome.exe', creationflags=DETACHED_PROCESS)`. This could fail if the program expects standard I/O. In that case try passing the `stdin`, `stdout`, and `stderr` arguments as `subprocess.PIPE`. There's also `CREATE_NO_WINDOW = 0x08000000`, which creates a new instance of conhost.exe with valid standard handles, just without a window. – Eryk Sun Jan 01 '16 at 06:42
  • Thanks to everyone who commented on this. I finally got it to work by using a VBS file on startup that runs a batch file which runs my python program. It sounds pretty inefficient, but it works for what I'm trying to accomplish. Thanks guys! – JustDucky Jan 01 '16 at 22:47

2 Answers2

3

Use windows 'start' command in your .cmd file; remove the 'exit'.
Like this:

cd C:\Users\(my name)\Desktop
start pythonw File.pyw
Generic Ratzlaugh
  • 717
  • 1
  • 6
  • 13
  • Dude, you just saved my day... I was getting genuinely upset on not being able to find out how to do this... Probably made alot of code changes that werent necessary, thank you so much for this answer! – Gloat Jan 05 '22 at 21:57
1

So, my final approach was just to link a VBS file (like it was mentioned in the comments.) It turned out I was doing it wrong, and mixing file types, so I had weird errors. That VBS file called a BAT file silently, so the cmd window didn't show up. That BAT file then called my program, which for some reason ran better when called from cmd than when it was just executed on the spot. Now, it does run on startup, and the cmd window doesn't appear, so it is a good fix, though inefficient.

JustDucky
  • 132
  • 1
  • 10