David
David

Reputation: 753

How to run a Python script without Windows console appearing

Is there any way to run a Python script without a command shell momentarily appearing? Naming my files with the ".pyw" extension doesn't work.

Upvotes: 5

Views: 18771

Answers (4)

Neal Garrett
Neal Garrett

Reputation: 185

The simple answer is to copy the "LazyLibrarian.py" to "LazyLibraryian.pyw" and create a shortcut to Desktop. Then put the shortcut in your startup folder.

Upvotes: 0

David
David

Reputation: 753

Use ShellExecuteEx function.

BOOL ShellExecuteEx(
_Inout_ SHELLEXECUTEINFO *pExecInfo
);

This is the pExecInfo: ***nShow - Flags that specify how an application is to be shown when it is opened

typedef struct _SHELLEXECUTEINFO {
  DWORD     cbSize;
  ULONG     fMask;
  HWND      hwnd;
  LPCTSTR   lpVerb;
  LPCTSTR   lpFile;
  LPCTSTR   lpParameters;
  LPCTSTR   lpDirectory;
  int       nShow;/*=0 if you don't want the console window to appear*/
  HINSTANCE hInstApp;
  LPVOID    lpIDList;
  LPCTSTR   lpClass;
  HKEY      hkeyClass;
  DWORD     dwHotKey;
  union {
    HANDLE hIcon;
    HANDLE hMonitor;
    } DUMMYUNIONNAME;
    HANDLE    hProcess;
} SHELLEXECUTEINFO, *LPSHELLEXECUTEINFO;

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140138

In all python installs since 2.5 (and possibly earlier), if the install has been done properly, .py files are associated to python.exe and .pyw files are associated to pythonw.exe

If the associations have been tampered with, or overridden for a particular user, that may be different.

Run the following command in a cmd:

ftype | find "pythonw"
assoc | find ".pyw"

I get:

 Python.NoConFile="D:\Program Files\Python27\pythonw.exe" "%1" %*
.pyw=Python.NoConFile

If you don't have that, you can do several things to fix that:

  1. re-install/repair python installation (run installer, it will propose to repair install)
  2. if you're not administrator of your machine, you can associate .pyw files to pythonw.exe. Minor problem with that, you have to alter the registry key afterwards to add the extra arguments or dropping a parameter on your .pyw file won't take it into account (it's seldom used but still)

    [HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command] @="\"L:\\Portable_Python_2.7.3.1\\App\\pythonw.exe\" \"%1\" %*"

Upvotes: 2

Ramón Gil Moreno
Ramón Gil Moreno

Reputation: 819

Try using the Python's pythonw.exe executable to start your script.

In Windows OSes, executables that are console applications (python.exe with out the w is a console app) are run showing a console window; in the other hand regular Windows applications do not spawn that black console window.

You can find the details about these two executables in this old question: pythonw.exe or python.exe?

And about Windows different types of applications here: Difference between Windows and Console application

Upvotes: 7

Related Questions