我正在尝试使我的 Python 程序与 Linux 兼容,但老实说,我不知道如何编写 Shell 脚本。自从我开始使用这个程序以来,我确实知道一些批处理脚本。
@echo off
chcp 65001 > NUL
cd /d "%~dp0"
if exist %SYSTEMROOT%\py.exe (
cmd /k C:\Windows\py.exe -3.5 -m pip install --upgrade -r Requirements.txt
exit
)
python --version > NUL 2>&1
if %ERRORLEVEL% NEQ 0 goto nopython
cmd /k python -m pip install --upgrade -r requirements.txt
goto end
:nopython
echo ERROR: Git has either not been installed or not been added to your PATH
:end
pause
有没有人有时间帮助我将其作为 shell 脚本运行,以便可以在 linux 上执行?
答案1
@echo off
由于 shell 脚本默认不回显命令,因此不需要等效命令。
if exist %SYSTEMROOT%\py.exe (
cmd /k C:\Windows\py.exe -3.5 -m pip install --upgrade -r Requirements.txt
exit
)
Linux 系统不使用启动py
器。而是调用pip3
。系统安装pip3
(即使用包管理器安装)的等价物是/usr/bin/pip3
:
if [ -x /usr/bin/pip3 ]
then
/usr/bin/pip3 install --upgrade -r Requirements.txt
exit
fi
但是,最好使用任何可用的pip3
:
if command -v pip3 > /dev/null
then
pip3 install --upgrade -r Requirements.txt
exit
fi
command -v
可用于检查程序是否在 中PATH
(它会打印该程序的路径,我们使用 将其丢弃> /dev/null
)。您还可以检查python3
并运行python3 -m pip
。
python --version > NUL 2>&1
if %ERRORLEVEL% NEQ 0 goto nopython
cmd /k python -m pip install --upgrade -r requirements.txt
goto end
:nopython
echo ERROR: Git has either not been installed or not been added to your PATH
:end
pause
我们没有goto
shell 脚本。
等效的例子如下:
python --version 2>&1 > /dev/null # Note the order of redirections
if [ $? != 0 ] # $? is like ERRORLEVEL
then
echo ERROR: Git has either not been installed or not been added to your PATH
else
python -m pip install --upgrade -r requirements.txt
fi
在我看来,哪个更具可读性,因为:
if python --version 2>&1 > /dev/null
then
python -m pip install --upgrade -r requirements.txt
else
echo ERROR: Git has either not been installed or not been added to your PATH
fi
边注:Git还没有安装吗?oo