Get python executable full path from C++
<p>I have a program, written in C++. I would like to get full path to python executable from it. For example, if I open Windows command prompt (cmd.exe) and type python, it use python executable from <code>PATH</code>. So, i would like to have a function <code>get_exec_path("python")</code> whick returns something like <code>C:\Python27\python.exe</code>. <code>C:\Python27\</code> is in my <code>PATH</code>.
I need this for calling python scripts from C++ code. Embedding python in C++ is a bad idea for my purposes. I used to call it like this:</p>

<pre><code>std::system("start \"\" /WAIT python myscript.py --arg1 arg1 --arg2 arg2")
</code></pre>

<p>but this method shows command prompt window, I would like some kind of background work. For this purpose I used <code>CreateProcess</code> with second argument <code>"C:\Python27\python.exe myscript.py --arg1 arg1 --arg2 arg2"</code>. So, I need full path to python executable from <code>PATH</code> variable.</p>

<p>As you a showing a Windows Python path, this answer will focus on Windows and is <strong>not</strong> portable.</p>

<p>A function from the shwlapi does exactly what you want: </p>

<pre><code>BOOL PathFindOnPath(
  _Inout_  LPTSTR  pszFile,
  _In_opt_ LPCTSTR *ppszOtherDirs
);
</code></pre>

<p>Its <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb773594%28v=vs.85%29.aspx" rel="nofollow">documentation</a> says:</p>

<blockquote>
  <p>PathFindOnPath searches for the file specified by pszFile. If no directories are specified in ppszOtherDirs, it attempts to find the file by searching standard directories such as System32 and the directories specified in the PATH environment variable.</p>
</blockquote>

<p>To find for python.exe you could do:</p>

<pre><code>char path[MAX_PATH] = "python.exe";
BOOL cr = ::PathFindOnPathA(path, NULL);
if (! cr) {
    //process error ...
}
// path now contains the full path
</code></pre>

<p>BEWARE: you must include shlwapi.h and link shlwapi.lib ...</p>

python c++