Windows系统PyCharm右键运行.sh文件

在参考了Windows系统下pycharm运行.sh文件,执行shell命令_shell在pycharm-CSDN博客

深度学习:PyCharm中运行Bash脚本_pycharm bash-CSDN博客

配置了右键执行.sh文件之后,发现在Windows的PyCharm中直接右键运行sh文件,存在如下问题:

  1. 有些命令在Linux中能正常运行,Windows中却不能,例如xargs、source、&&等

  2. 即使配置成sh.exe也只能通过在Terminal中输入脚本路径来运行它,无法做到在左侧文件导航目录那里,点右键直接运行

===========================

最终,我把所有.sh脚本全部,全部改成了.py文件,然后使用subprocess.run来运行shell命令。

例如:

原文件 -- scripts/format.sh

bash 复制代码
#!/bin/sh -e
set -x

[ -f pyproject.toml ] || ([ -f ../pyproject.toml ] && cd ..)

SKIP_MYPY=1 pdm run fast lint

修改后 -- scripts/format.py

python 复制代码
#!/usr/bin/env python
import os
import shlex
import subprocess
import sys
from pathlib import Path

work_dir = Path(__file__).parent.resolve().parent
if Path.cwd() != work_dir:
    os.chdir(str(work_dir))

cmd = "pdm run fast lint"
r = subprocess.run(shlex.split(cmd), env=dict(os.environ, SKIP_MYPY="1"))
sys.exit(None if r.returncode == 0 else 1)

修改之后,就可以直接右键运行了,如下图:

更多示例,可以通过如下方式查看:

bash 复制代码
git clone git@github.com:waketzheng/fast-dev-cli.git
cd fast-dev-cli
git diff v0.10.0 v0.10.1 scripts/

注:如果要执行的shell命令是以python开头的,如`python -m fast_dev_cli lint`,若系统中有多个版本的python解释器,最好把其中的python改成Path(sys.executable),如:

bash 复制代码
#!/usr/bin/env python
import shlex
import subprocess
import sys
from pathlib import Path

cmd = "python -m fast_dev_cli lint"
command = shlex.split(cmd)
r = subprocess.run([Path(sys.executable), *command[1:]])
sys.exit(None if r.returncode == 0 else 1)
相关推荐
Lyn_Li2 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸6 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学7 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python