通过一个 .bat 文件激活 Activate.ps1,自动打开一个带有 venv 指令的笔记本。

huangapple go评论60阅读模式
英文:

Activate.ps1 through a .bat file auto opens a notebook with venv instructions

问题

Hi everyone!

Kinda new to venvs. I've created one through Powershell and I activate with a .bat file, it works normally but it also seems to open the Activate.ps1 in my VS like a Notebook or txt file.

I can close or leave it and the program works fine but I don't know if this is Python/.bat/.ps1 error or even a normal behavior, but I don't want it opening, if possible.

After searching I found this post here: Typing venv scripts activate.ps1 open Notebook auto

But the post has 1 answer that does not solve my problem, and it's a bit different since my program works fine even if this file auto opens.

-using python 3.10.4

venv creation:

cd C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\
python -m venv "C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo";

Nome_Projeto\Nome_do_Robo\Scripts\Activate.ps1
python -m pip install --upgrade pip

pip install -r "C:\Users\Me\Documents\DATA_SCIENCE\Projetos\_infos\Requirements\requirements_Robo.txt"

.bat file:

@echo off
setlocal

cd C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo\Scripts\
set PYTHONPATH=C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo\Scripts\
set pathLog=C:\Users\Me\Documents\DATA_SCIENCE\Projetos\_Logs\Nome_Projeto
.
.(Others string variables)
.
set resultado=C:\Users\Me\Documents\DATA_SCIENCE\Projetos\_Resultados_dos_Robos\Nome_Projeto\
taskkill /IM python.exe /F
C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo\Scripts\Activate.ps1 & python C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\ScrapStuff.py

I ran the .bat file in Powershell and VS Studio, both open the following note (looks like a "how-to venv help" file)

(File is really long but if needed I paste the whole content)

英文:

Hi everyone!

Kinda new to venvs. I've created one through Powershell and I activate with a .bat file, it works normally but it also seems to open the Activate.ps1 in my VS like a Notebook or txt file.

I can close or leave it and the program works fine but i don't know if this is Python/.bat/.ps1 error or even a normal behavior, but I don't want it opening, if possible.

After searching I found this post here: Typing venv scripts activate.ps1 open Notebook auto

But the post has 1 answer that does not solve my problem, and its a bit different since my program works fine even if this file auto opens

-using python 3.10.4

venv creation:

cd C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\
python -m venv "C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo"


Nome_Projeto\Nome_do_Robo\Scripts\Activate.ps1
python -m pip install --upgrade pip

pip install -r "C:\Users\Me\Documents\DATA_SCIENCE\Projetos\_infos\Requirements\requirements_Robo.txt"

.bat file:

@echo off
setlocal


cd C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo\Scripts\
set PYTHONPATH=C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo\Scripts\

set pathLog=C:\Users\Me\Documents\DATA_SCIENCE\Projetos\_Logs\Nome_Projeto
.
.(Others string variables)
.
set resultado=C:\Users\Me\Documents\DATA_SCIENCE\Projetos\_Resultados_dos_Robos\Nome_Projeto\


taskkill /IM python.exe /F


C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\Nome_do_Robo\Scripts\Activate.ps1 & 
python C:\Users\Me\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\ScrapStuff.py

I ran the .bat file in Powershell and VS Studio, both opens the following note (looks like a "how-to venv help" file)

(File is really long but if needed I paste the whole content)

<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.

.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.

.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.

.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').

.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.

.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.

.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.

.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.

.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:

PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

For more information on Execution Policies: 
https://go.microsoft.com/fwlink/?LinkID=135170

#>
Param(
    [Parameter(Mandatory = $false)]
    [String]
    $VenvDir,
    [Parameter(Mandatory = $false)]
    [String]
    $Prompt
)

<# Function declarations --------------------------------------------------- #>

I have 3 basic scripts that run in this venv, if needed i can share it also

Any help would be appreciated!

Thanks!

Deleted the venv and folder, restarted Desktop and re-created the entire venv in other folder.

答案1

得分: 1

以下是代码的翻译部分:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
cd /D "%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\Nome_Projeto"
if not errorlevel 1 goto TerminatePython

echo 错误: 目录 "%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\Nome_Projeto" 不存在.
echo(
pause
exit /B 1

:TerminatePython
rem 优雅地终止所有正在运行的 Python 进程。
%SystemRoot%\System32\taskkill.exe /IM python.exe

call "Nome_do_Robo\Scripts\Activate.bat"

set "pathLog=%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\_Logs\Nome_Projeto"
rem .
rem .(其他字符串变量)
rem .
set "resultado=%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\_Resultados_dos_Robos\Nome_Projeto\"

python.exe "%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\ScrapStuff.py"
endlocal

上述是批处理文件的翻译部分,其中包括设置环境变量、切换目录、终止 Python 进程、调用 Activate.bat 文件等操作。如果您需要关于其他部分的翻译或进一步的解释,请告诉我。

英文:

The batch file should be as follows:

<!-- language: lang-none -->

@echo off
setlocal EnableExtensions DisableDelayedExpansion
cd /D &quot;%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\Nome_Projeto&quot;
if not errorlevel 1 goto TerminatePython

echo ERROR: Directory &quot;%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\Nome_Projeto&quot; does not exist.
echo(
pause
exit /B 1

:TerminatePython
rem Gracefully terminate ALL currently running Python processes.
%SystemRoot%\System32\taskkill.exe /IM python.exe

call &quot;Nome_do_Robo\Scripts\Activate.bat&quot;

set &quot;pathLog=%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\_Logs\Nome_Projeto&quot;
rem .
rem .(Others string variables)
rem .
set &quot;resultado=%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\_Resultados_dos_Robos\Nome_Projeto\&quot;

python.exe &quot;%USERPROFILE%\Documents\DATA_SCIENCE\Projetos\Nome_Projeto\ScrapStuff.py&quot;
endlocal

The first two command lines define completely the required execution environment for the batch file processing by the Windows Command Processor cmd.exe which interprets batch files. The batch file works for that reason independent on the environment defined outside of the batch file by the process starting cmd.exe or another batch file which perhaps calls this batch file.

The third command line changes the current directory which of course can fail if the directory does not exist anymore.

If the change of the current directory fails, an appropriate error message is output as well as an empty line and a prompt for any key press to halt batch file processing to give the user a chance to read the error message on having started the batch file with a double click in file manager. Then the batch file processing is exited with exit code 1 for indicating an error for the parent process and cmd.exe runs implicit endlocal to restore the initial execution environment.

There are gracefully terminated next all running Python processes by calling TASKKILL without its option /F. The fully qualified file name of TASKKILL is used to avoid that cmd.exe needs to search for this executable in file system which makes the batch file also working on system or local environment variable PATH being corrupted somehow.

TASKKILL sends to all running python.exe processes the WM_CLOSE message which usually results in python.exe stops interpreting the Python script, closing all currently opened files with saving data in stream buffers of files opened for write operations, closing all connections and terminating.

The usage of TASKKILL option /F would cause a brutal kill of all running Python processes by the Windows operating system without giving them the chance to do all the actions required for a graceful self-termination.

The PowerShell script file Activate.ps1 is for definition of the Python environment in a PowerShell console or a PowerShell script. It contains PowerShell cmdlets to define environment variables in memory of %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe.

The Windows Command Processor does not know what to do with a file with file extension .ps1. It calls for that reason the ShellExecuteEx function which first looks up the default string value in Windows registry of HKEY_CLASSES_ROOT\.ps1 which is Microsoft.PowerShellScript.1. It looks up next the default string value of HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command which is &quot;C:\Windows\System32\notepad.exe&quot; &quot;%1&quot;. Then ShellExecuteEx starts Windows Notepad with the fully qualified file name of the PowerShell script file as argument for editing it by the user.

This behavior is not wanted here. There should be activated the Python environment with (re)definition of environment variables in memory of cmd.exe processing the batch file. There must be called for that reason the batch file Activate.bat in the Scripts subdirectory of the environment directory Nome_do_Robo using the cmd internal command call. That is the most important modification to get the batch file working as expected.

There is called python.exe with the fully qualified file name of the Python script file to run as argument after definition of several environment variables.

The Windows Command Processor halts the batch file processing now until the Python executable terminated itself. Then there is executed explicitly the cmd internal command endlocal to restore the initial environment before exiting processing of the batch file because of reaching its end.

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • call /?
  • cd /?
  • echo /?
  • endlocal /?
  • exit /?
  • if /?
  • pause /?
  • rem /?
  • set /?
  • setlocal /?
  • taskkill /?

Note: &amp; at end of a Linux/Mac shell script command line instructs the shell interpreter to start the executable or the interpreter of a script file specified left in background with capturing all output to standard output and standard error streams of the started executable and output it on own standard output and error stream and continue processing the current script or lettig the user enter more commands to execute in current terminal window. The Windows Command Processor interprets an ampersand outside a double quoted argument string as unconditional command operator as described by single line with multiple commands using Windows batch file. The character &amp; at end of a command line in a Windows batch file makes therefore never sense. The Windows batch file equivalent of &amp; at end of a Linux/Mac shell script command line would be the usage of command start with option /B.

Please read DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ why echo( is used to output an empty line. cmd.exe does not access the file system on using echo( in comparison to echo. or echo/ and runs just its internal command echo to output an empty line.

huangapple
  • 本文由 发表于 2023年3月23日 08:36:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75818375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定