2

Is it possible to run a .py script from CLI using python27.dll? I have tried this:

rundll32.exe python27.dll,PyRun_SimpleString "import myScript.py"

but seems not to work.

The situation is that I can install all python modules I want, but no executables, so I cannot install full Python.

luca.vercelli
  • 898
  • 7
  • 24
  • you can convert into executable file then you do not need to install full python setup for execution.If you are using window convert into .exe format. check the video ==>https://www.youtube.com/watch?v=vPzc4OelblQ – rohitjoshi9023 Oct 11 '17 at 13:43

1 Answers1

3

You can't do this. Why?

Windows contains a command-line utility program named rundll32.exe that allows you to invoke a function exported from a 32-bit DLL using the following syntax:

RUNDLL.EXE <dllname>,<entrypoint> <optional arguments>

But, according to MSDN:

Rundll32 programs do not allow you to call any exported function from any DLL

[..]

The programs only allow you to call functions from a DLL that are explicitly written to be called by them.

The dll must export the following prototype to support it:

void CALLBACK EntryPoint(HWND hwnd, HINSTANCE hinst,
                         LPSTR lpszCmdLine, int nCmdShow);

Since python.dll doesn't export such an entry point, you have to write a wrapper application in C/C++ that loads the dll and uses it, for example (here is a snippet from such an application):

// load the Python DLL
#ifdef _DEBUG
LPCWSTR pDllName = L"python27_d.dll" ;
#else
LPCWSTR pDllName = L"python27.dll" ;
#endif

HMODULE hModule = LoadLibrary( pDllName ) ;
assert( hModule != NULL ) ;
 
// locate the Py_InitializeEx() function
FARPROC pInitializeExFn = GetProcAddress( hModule , "Py_InitializeEx" ) ;
assert( pInitializeExFn != NULL ) ;
 
// call Py_InitializeEx()
typedef void (*PINITIALIZEEXFN)( int ) ;
((PINITIALIZEEXFN)pInitializeExFn)( 0 ) ;

FILE* fp ;
errno_t rc = fopen_s( &fp , pFilename , "r" ) ;
assert( rc == 0 && fp != NULL ) ;

[..] // go on to load PyRun_SimpleFile
if ( 0 == PyRun_SimpleFile( fp , pFilename )
    printf("Successfully executed script %s!\n", pFilename);

Origin: Awasu.com first and second tutorials

Daniel Trugman
  • 8,186
  • 20
  • 41
  • <>: I don't think so, rundll32.exe is done for that purpose exactly, I think. – luca.vercelli Oct 11 '17 at 14:21
  • @luca.vercelli, I now see that my explanation wasn't clear enough, so I elaborated – Daniel Trugman Oct 11 '17 at 14:35
  • You've provided excellent sources, however I can't seem to find a source to verify that "python.dll doesn't export such an entry point"? – micsthepick Jul 20 '23 at 23:16
  • 1
    @micsthepick, this was a long time ago. You can check that yourself by examining your Python DLL. See this thread for tools that can help enumerate all the exported functions from a DLL: https://stackoverflow.com/questions/1548637/is-there-any-native-dll-export-functions-viewer – Daniel Trugman Jul 22 '23 at 12:28