4
votes

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.

EDIT: problem solved with ShellExecute()

4
Can you tell us more about how you used the ShellExecute()? - bkbilly
@bkbilly I have published my own answer to this question. You may find it below. - David

4 Answers

6
votes

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

2
votes

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\" %*"

0
votes

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;
0
votes

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.