Equivalent to Unix eval in Windows

后端 未结 2 1403
轻奢々
轻奢々 2020-12-16 17:28

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 outpu

相关标签:
2条回答
  • 2020-12-16 17:55

    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
    
    0 讨论(0)
  • 2020-12-16 17:58

    (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.

    1. 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 like goto than gosub. The CMD process just switches from one script to another.

    2. 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. When q.bat exits, control will return to the caller. Since this is the same CMD process, changes to the environment will still be there.

      Note: If q.bat uses the EXIT statement, it can cause the CMD process to terminate, without returning control to the calling script.


      Note 2: If q.bat uses EXIT /B, then the CMD process will not exit. This is useful for setting ERRORLEVEL.

    3. 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: If q.bat uses EXIT, 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"
    

    0 讨论(0)
提交回复
热议问题