Python呼び出し(実行)外部プログラムパラメータの問題

4905 ワード

ShellExecuteとCreateProcess
ShellExecute
ShellExecute(hwnd,op,file,params,dir,bShow)のパラメータの意味は以下の通りです.hwnd:親ウィンドウのハンドルで、親ウィンドウがない場合は0です.op:実行する操作は、「open」、「print」、または空です.file:実行するプログラム、または開くスクリプト.params:プログラムに渡すパラメータは、ファイルとして開いている場合は空です.dir:プログラム初期化のディレクトリ.bShow:ウィンドウを表示するかどうかは理解できますが、ShellExecuteを使用するとwindowsの下のcmdでexeファイルを呼び出すようになります.
CreateProcess
スクリプトで実行されるプログラムの制御を容易にするために、win 32 processモジュールのCreateProcess()関数を使用します.その関数のプロトタイプを以下に示します.CreateProcess(appName,commandLine,processAttributes,threadAttributes,bInheritHandles,dwCreationFlags,newEnvironment,currentDirectory,startupinfo)のパラメータの意味は次のとおりです.appName:実行可能なファイル名.commandLine:コマンドラインパラメータ.processAttributes:プロセスセキュリティ属性、Noneの場合はデフォルトのセキュリティ属性.threadAttributes:スレッドセキュリティ属性、Noneの場合はデフォルトのセキュリティ属性.bInheritHandles:継承フラグ.dwCreationFlags:フラグを作成します.新環境:プロセスの環境変数を作成します.CurrentDirectory:プロセスの現在のディレクトリ.startupinfo:プロセスのプロパティを作成します.CreateProcess呼び出しexeはShellExecute呼び出しと若干異なり,主にパラメータの伝達が異なる.次に例として説明する
Example
簡単なC++コードを作成し、exeファイルを生成します.コードは以下の通りです.
#include 
#include 

using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "hello nothing" << endl;
        cin.get();
        return -1;
    }

    for (int i = 1; i < argc; ++i)
    {
        cout << argv[i] << endl;
    }
    cin.get();
    return 0;
}

ShellExecute呼び出しの使用
#usr/bin/env python
#-*- coding: utf-8 -*-

import win32api
import win32event
import win32process

def main():
    exePath = "E:\python_wk\callExeOnWin\helloSomething.exe"
    param = "hello world abc 123"
    win32api.ShellExecute(0,
                        "open",
                        exePath,
                        param,
                        '',
                        1)
if '__main__' == __name__:
    main()

パラメータがスペースで区切られているのがわかります
CreateProcess呼び出しの使用
#usr/bin/env python
#-*- coding: utf-8 -*-

import win32api
import win32event
import win32process
def main():
    exePath = "E:\python_wk\callExeOnWin\helloSomething.exe"
    param = "hello world abc 123"

    param = exePath + " " + param

    handle = win32process.CreateProcess(exePath,
                                    param,
                                    None,
                                    None,
                                    0,
                                    win32process.CREATE_NEW_CONSOLE,
                                    None,
                                    None,
                                    win32process.STARTUPINFO())
if '__main__' == __name__:
    main()

C++によってコンパイルされたexeファイルの最初のパラメータは自己であるため、すなわちC++プログラムにおけるargv[0]の値はexeファイルそのもののパスであり、CreateProcessを使用してexeを呼び出す場合、我々はexeパスをパラメータに加える必要があり、ShellExecuteでは不要であることがわかる.