简体   繁体   中英

Run python script using python27.dll

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.

You can't do this. Why?

Windows contains a command-line utility programs named rundll32.exe that allow you to invoke a function exported from a 32-bit DLLs 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM