问题
Was wondering how you'd do the following in Windows:
From a c shell script (extension csh), I'm running a Python script within an 'eval' method so that the output from the script affects the shell environment. Looks like this:
eval `python -c "import sys; run_my_code_here(); "`
Was wondering how I would do something like the eval statement in Windows using Windows' built in CMD shell. I want to run a Python script within a Windows script and have the script run what the Python script prints out.
** update: specified interest in running from CMD shell.
回答1:
If it's in cmd.exe, using a temporary file is the only option [that I know of]:
python -c "print(\"Hi\")" > temp.cmd
call temp.cmd
del temp.cmd
回答2:
(Making some guesses where details are missing from your question)
In CMD, when a batch script modifies the environment, the default behavior is that it modifies the environment of the CMD process that is executing it.
Now, if you have a batch script that calls another batch script, there are 3 ways to do it.
execute the batch file directly:
REM call q.bat q.bat REM this line never runs
Usually you don't want this, because it won't return to the calling batch script. This is more likegotothangosub. The CMD process just switches from one script to another.execute with
call:REM call q.bat CALL q.bat REM changes that q.bat affects will appear here.
This is the most common way for one batch file to call another. Whenq.batexits, control will return to the caller. Since this is the same CMD process, changes to the environment will still be there.
Note: Ifq.batuses theEXITstatement, it can cause the CMD process to terminate, without returning control to the calling script.
Note 2: Ifq.batusesEXIT /B, then the CMD process will not exit. This is useful for settingERRORLEVEL.Execute in a new CMD process:
REM call q.bat CMD /C q.bat REM environment changes in q.bat don't affect me
Since q.bat run ins a new CMD process, it affects the environment of that process, and not the CMD that the caller is running in.
Note: Ifq.batusesEXIT, it won't terminate the process of the caller.
The SETLOCAL CMD command will create a new environment for the current script. Changes in that environment won't affect the caller. In general, SETLOCAL is a good practice, to avoid leaking environment changes by accident.
To use SETLOCAL and still push environment changes to the calling script, end the script with:
ENDLOCAL && SET X=%X% && SET Y=%Y%
This will push the values of X and Y to the parent environment.
If on the other hand you want to run another process (not a CMD script) and have it affect the current script's environment, than have the tool generate a batch file that makes the changes you want, then execute that batch file.
REM q.exe will write %TEMP%\runme.cmd, which looks like:
REM set X=Y
q.exe
call "%TEMP%\runme.cmd"
来源:https://stackoverflow.com/questions/1195494/equivalent-to-unix-eval-in-windows