简体   繁体   English

如何从 Windows 上的 C++ 程序在虚拟环境中启动 python 脚本?

[英]How to launch a python script in a virtual environment from a C++ program on Windows?

So far I am using a 2-step approach and launch cmd.exe rather than python.exe .到目前为止,我使用的是两步方法并启动cmd.exe而不是python.exe But I don't like cmd.exe in between the process tree for several reasons (eg I don't receive the python process handle or ID, but rather the one of cmd.exe ).但我不喜欢cmd.exe在进程树之间有几个原因(例如,我没有收到 python 进程句柄或 ID,而是cmd.exe之一)。

string sCmd =
  "cmd.exe /C venv\\SomeEnv\\Scripts\\activate.bat && python.exe Subprograms\\my_script.py";
CreateProcessA(nullptr,
  sCmd.data(),
  ...);

I believe that to activate the virtual environment I need to put it at the beginning of the PATH environment variable and set some other variables like PYTHONHOME and PYTHONPATH , but I'm not sure whether this is sufficient and what values to set there on Windows.我相信要激活虚拟环境,我需要将它放在PATH环境变量的开头并设置一些其他变量,如PYTHONHOMEPYTHONPATH ,但我不确定这是否足够以及在 Windows 上设置什么值。

If you want to do it using standard C++, you can go for std::system()

std::system("command_to_run_with_space_separated_params_if_any");

If you want to use windows ways, you can go for followings...
  ShellExecuteEx()
  ShellExecute()
  CreateProcessA()
  CreateProcessW()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Windows XP中从C ++程序执行Python脚本 - Executing Python Script from C++ program in Windows XP 如何从虚拟环境(virtualenv)启动 python Idle - How to launch python Idle from a virtual environment (virtualenv) 如何从 windows 命令提示符在虚拟环境中运行 python 程序? - How do I run a python program in a virtual environment from windows command prompt? 如何在 WSL Ubuntu 20.04 环境中从 Windows 中的 Python 脚本启动命令 - How can I launch commands from a Python script in Windows in a WSL Ubuntu 20.04 environment 如何在Mac上的bash脚本中激活Python虚拟环境并启动python脚本? - How can I activate a Python virtual environment and launch a python script, in a bash script on Mac? C# 从虚拟环境运行 python 脚本 - C# run python script from virtual environment 你如何从 C++ 程序运行 python 脚本? - How do you run a python script from a C++ program? 如何从Windows中的ac程序执行python(2.7)脚本 - how to execute a python (2.7) script from a c program in Windows 如何在没有cmd的虚拟环境中使用python运行python脚本 - How to run python script with python from virtual environment without cmd 从 python 脚本激活虚拟环境 - Activate virtual environment from a python script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM