我正在尝试在BAT文件中打开一个新的命令窗口:

start %windir%\system32\cmd.exe

打开后,我想在新窗口中执行BAT命令:

echo "test in new window"

我该怎么做呢?


当前回答

我需要运行一个环境,然后在该环境中使用python。

如果我的文件夹结构是:

C:\environments>
C:\environments\encrypted_stuff>
C:\environments\encrypted_stuff\p1>
C:\environments\encrypted_stuff\p2>

我想激活“encrypted_stuff”环境,然后从p2调用一个脚本,我可能会在存储在C:\environments\p2.bat中的bat中输入这个脚本

start cmd /k "Scripts\activate && cd p2 && python p2_script.py"

然后我可以有一个bat文件的任何脚本和所有将使用我的“encrypted_stuff”环境。现在我可以从桌面上单击bat文件,它将加载我的特定环境,然后在该环境中运行脚本。

其他回答

我需要运行一个环境,然后在该环境中使用python。

如果我的文件夹结构是:

C:\environments>
C:\environments\encrypted_stuff>
C:\environments\encrypted_stuff\p1>
C:\environments\encrypted_stuff\p2>

我想激活“encrypted_stuff”环境,然后从p2调用一个脚本,我可能会在存储在C:\environments\p2.bat中的bat中输入这个脚本

start cmd /k "Scripts\activate && cd p2 && python p2_script.py"

然后我可以有一个bat文件的任何脚本和所有将使用我的“encrypted_stuff”环境。现在我可以从桌面上单击bat文件,它将加载我的特定环境,然后在该环境中运行脚本。

以上的答案对我很有帮助。但仍然需要一些思考。下面是一个示例脚本,我用来启动3个过程的web开发。这导致3个窗口保持打开状态,因为它们需要持续运行。

Mongo被全局添加到我的路径中,所以我不需要像对其他两个程序那样进行cd。当然,文件的路径会有所不同,但希望这对您有所帮助。

:: Start MongoDB
start cmd.exe /k "mongod"

:: cd app directory, and start it
cd my-app
start cmd.exe /k "npm run dev"

:: cd to api server, and start that
cd ../my-app-api
start cmd.exe /k "npm run dev"

如果我正确理解你这样做在一边你的bat文件将打开命令提示符和打印你的消息到屏幕上。

cmd.exe hello world

希望这能有所帮助。

在一个新的CMD窗口中运行一个python文件,文件名中有空格。

start cmd.exe /k python "C:\Program Files\HelloWorld.py"

这并不容易。

最好的方法是将希望在“新窗口”中执行的脚本部分放在单独的.bat文件中。这可能是不切实际的,例如,你需要从你的脚本的其他部分(变量等)很多状态。一种选择是将你需要的任何值(例如dir)传递给批处理文件:

start cmd.exe stuff.bat %this_dir%

如果你有大量的状态要传输,你可以考虑在运行时生成一个批处理文件:

set foo=Hello, World
set list_me=%userprofile%

set tmpdir=c:\windows\temp
set tmp=%tmpdir%\tmp.foo

del /q /f "%tmp%"

echo.echo %foo%>>"%tmp%"
echo.dir "%list_me%">>>"%tmp"

start cmd.exe "%tmp%"

del /q /f "%tmp%"

显然这是一个简单的例子。