简体   繁体   中英

Save output of a command as a variable (Windows command prompt)

Say I have the command:

python --version > PythonVersion.txt

A file called PythonVersion.txt is created. In my case the contents are "Python 3.9.13".

Can the output of a command be saved as a variable? I'd like to be able to do something like the following:

@echo off
set "PythonVersion=python --version"
echo Your Python installation is: %PythonVersion%

The expected output might be Your Python installation is: Python 3.9.13 , but of course the above script isn't valid and produces Your Python installation is: python --version .

@echo off
for /F "delims=" %%a in ('python --version') do @set lastline=%%a
echo.%lastline%

If the output is multiple lines, you might have to filter the command output with ^| find... ^| find... to just get the line you are interested in (unless you want the last line) because for will loop until there are no more non-empty lines...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM