Skip to main content
 首页 » 编程设计

python之使用 python27.dll 运行 python 脚本

2024年10月01日7zfyouxi

是否可以使用 python27.dll 从 CLI 运行 .py 脚本? 我试过这个:

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

但似乎不起作用。

情况是我可以安装我想要的所有 python 模块,但没有可执行文件,所以我无法安装完整的 Python。

请您参考如下方法:

你不能这样做。为什么?

Windows 包含一个名为 rundll32.exe 的命令行实用程序,它允许您使用以下语法调用从 32 位 DLL 导出的函数:

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

但是,根据 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.

dll 必须导出以下原型(prototype)以支持它:

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

因为 python.dll 没有导出这样的入口点,你必须用 C/C++ 编写一个包装器应用程序来加载 dll 并使用它,例如(这里是来自这样的应用程序):

// 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); 

来源:Awasu.com first和 second教程