73

Is there any way to run a Python script in Windows XP without a command shell momentarily appearing? I often need to automate WordPerfect (for work) with Python, and even if my script has no output, if I execute it from without WP an empty shell still pops up for a second before disappearing. Is there any way to prevent this? Some kind of output redirection perhaps?

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
twneale
  • 2,836
  • 4
  • 29
  • 34

11 Answers11

136

pythonw.exe will run the script without a command prompt. The problem is that the Python interpreter, Python.exe, is linked against the console subsystem to produce console output (since that's 90% of cases) -- pythonw.exe is instead linked against the GUI subsystem, and Windows will not create a console output window for it unless it asks for one.

This article discusses GUI programming with Python, and also alludes to pythonw.exe. It also helpfully points out that if your Python files end with .pyw instead of .py, the standard Windows installer will set up associations correctly and run your Python in pythonw.exe.

In your case it doesn't sound like a problem, but reliance upon pythonw.exe makes your application Windows-specific -- other solutions exist to accomplish this on, say, Mac OS X.

Jed Smith
  • 15,584
  • 8
  • 52
  • 59
  • 1
    Is there a way to specify inside the python script weather to use `python.exe` or `pythonw.exe`? For example, `def prog_a(): run_as_pythonw() blah blah` vs. `def prog_b(): run_as_python() blah blah`. A switch-to-silent mode, if you will. – bmikolaj Dec 02 '15 at 21:24
  • 2
    Its not working like you explained to use pythonw.exe for .pyw. Can you please update the answer. its 2016 –  Feb 22 '16 at 17:48
  • 2
    If your `program.pyw` still pops up a console window, it could be because you have an incorrect #! line at the beginning of the program. (Found out the hard way when copying a GUI program written for Linux — and starting with `#!/usr/bin/env python` — to Windows 7.) Just remove that line. – ASL Jun 12 '19 at 17:04
37

If you name your files with the ".pyw" extension, then windows will execute them with the pythonw.exe interpreter. This will not open the dos console for running your script.

Peter Shinners
  • 3,686
  • 24
  • 24
10

This will work on all Windows Versions:

1. Create "Runner.bat" file with Notepad (or any other text editor) and insert following content:

@echo off
python server.py

where server.py is the path of the Python script you want to run.

2. Create "RunScript.vbs" file with Notepad and insert following content:

CreateObject("Wscript.Shell").Run "runner.bat",0,True

3. Run the "RunScript.vbs" file with double click and your Python script will be runnig without any visible console windows

p.s. I know that this was not part of your question but it is often the case, if you want to run the script on windows start (after user login) just paste the shortcut of "RunScript.vbs" file into your startup folder. (On Windows 10 mostly under: C:\Users[USERNAME]\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup )

Best regards

A. Dzebo
  • 558
  • 6
  • 13
  • 1
    Thanks! How to do this has been bugging me for years and years. As a mouse-hater (as well as a DOS-prompt-window-hater) I primarily wanted to be able to start using the WinKey... but if you put a shortcut of the vbs file on the desktop you can also start (without prompt) by clicking. – mike rodent Aug 11 '22 at 17:18
  • One thing I found by experimentation: if you put `pythonw ...` in this .bat file it causes a prompt window to flash up for a second, but if you put `python ...` you don't get that. Puzzling and counter-intuitive! – mike rodent Aug 11 '22 at 17:48
  • Happy to help. Most of us will never know what exactly is going on behind the scenes. Personally, I'm happy when I get the thing working as expected and doing what I want it to do. Best regards – A. Dzebo Sep 13 '22 at 10:07
9

I tried methods above, however, a console stills appears and disappears quickly due to a Timer in my script. Finally, I found following code:

import ctypes
import os
import win32process

hwnd = ctypes.windll.kernel32.GetConsoleWindow()      
if hwnd != 0:      
    ctypes.windll.user32.ShowWindow(hwnd, 0)      
    ctypes.windll.kernel32.CloseHandle(hwnd)
    _, pid = win32process.GetWindowThreadProcessId(hwnd)
    os.system('taskkill /PID ' + str(pid) + ' /f')
W.Leto
  • 1,013
  • 11
  • 13
3

Quite easy in Win10:
Open a PowerShell and type this commands:

type nul > openWindowed.vbs
type nul > main.py
notepad openWindowed.vbs

Paste the next into your openWindowed.vbs file:

Set WshShell = CreateObject("WScript.Shell") 
WshShell.Run chr(34) & "C:\Users\path\to\main.py" & Chr(34), 0
Set WshShell = Nothing

The .vbs file will execute your main.py file without open a cmd. I use this a lot to the make.py files, because I don't know cmake scripting.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
BOT USER
  • 31
  • 1
  • I tried "type nul > openWindowed.vbs" and "nul > openWindowed.vbs".. both threw errors. It seems you're maybe just creating empty files here, right? Sorry, I know next to nothing about vbs or PowerShell. – mike rodent Feb 20 '21 at 18:14
3

Turn of your window defender. And install pyinstaller package using pip install pyinstaller .

After installing open cmd and type pyinstaller --onefile --noconsole filename.py

1

Change the file extension to .pyw and add the following line (changed accordingly to your python version) to the beginning of your script:

#! c:\\Users\\sohra\\AppData\\Local\\Programs\\Python\\Python38\\pythonw.exe

Now, if you double click on the file, it will be executed by pythonw.exe without the console window.

Sohrab
  • 181
  • 2
  • 4
  • The effect of this for me was to open the file in Notepad++ when I clicked on it. Also I need my Python files to work in both W10 and Linux. I assume that having this as the first line would produce an error in Linux. – mike rodent Aug 11 '22 at 17:09
1

The stanza works well via python.exe, whereas it fails with pythonw.exe. Even worse, there is no feasible mechanism to output to sysout or syserr. Therefore, I wrote the following C# program to start python without the Command Window:

public class Program
{
  private string python = @"D:\Libs\Python38\Python38_64\python.exe";
  private string args = "mdx_server.py";
  private string wkDir = "D:\\Program Files\\mdx-server";
    
  public static void Main(string[] args) {
    Program app = new Program();
    Console.WriteLine(app.python + " " + app.args + " " + app.wkDir);
    app.Exec();
    Console.WriteLine("Start done!");
  }

  private void runThread() {
    Process process = new Process();
    try {
      process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
      process.StartInfo.Arguments = args;

      process.StartInfo.CreateNoWindow = true;
      process.StartInfo.FileName = python;
      process.StartInfo.WorkingDirectory = wkDir;

      process.StartInfo.UseShellExecute = false;
      process.Start();
    } catch (Exception ex) {
      Console.WriteLine(ex.Message);
    }
  }

  public void Exec() {
    Thread _worker = new Thread(runThread);
    _worker.Start();
  }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Kellen
  • 121
  • 5
0

There are 2 options in Windows, I think:

  • Option 1

    1. Change the .py file extension to .pyw and replace python.exe with pythonw.exe at its very first line as follows (take care to replace <your_username>\\<your_path_to>):

      #! C:\\Users\\<your_username>\\<your_path_to>\\Scripts\\pythonw.exe
      
    2. Double click on .pyw script file to run it.

    3. Optionally, you can also create a shortcut to .pyw file, to customize its name, icon and keyboard shortcut as final launcher!

  • Option 2

    1. Leave the .py file extension and replace pythonw.exe with python.exe at its very first line as follows (take care to replace <your_username>\\<your_path_to>):

      #! C:\\Users\\<your_username>\\<your_path_to>\\Scripts\\python.exe
      
    2. Use a .vbs (Visual Basic Script) file with the following content as launcher of the .py file (you can use a .vbs file to also launch a .bat file without showing the prompt):

      Set WshShell = CreateObject("WScript.Shell") 
      WshShell.Run "C:\Users\<your_username>\<your_path_to>\Scripts\python.exe C:\Users\<your_username>\<your_path_to>\script.py", 0, True
      Set WshShell = Nothing
      
    3. Double click on .vbs file to run your .py script.

    4. Optionally, you can also create a shortcut to .vbs file, to customize its name, icon and keyboard shortcut as final launcher!

Riccardo Volpe
  • 1,471
  • 1
  • 16
  • 30
0

When you install Pyinstaller, you will be able to convert the .py into a .exe. In the settings you can change whether to show or not show the console window that python opened when the file is ran.

-2

I had the same problem. I tried many options, and all of them failed But I tried this method, and it magically worked!!!!!

So, I had this python file (mod.py) in a folder, I used to run using command prompt When I used to close the cmd the gui is automatically closed.....(SAD), So I run it as follows C:\....>pythonw mod.py Don't forget pythonw "w" is IMP

  • I have .bat file which is (on Windows 10) C:\Users\XXXV\AppData\Local\Microsoft\WindowsApps\pythonw.exe C:\Scripts\p1.pyw but still the command console shows up and remains there until the python script is finished executing – Geo V Oct 27 '21 at 14:17
  • maybe if you read the answers before posting you would realize two people already provided this solution. – vdegenne Mar 09 '22 at 11:03