如何在Python中创建build文件或sh文件实现代码自动编译运行
针对Python代码创建一键运行脚本的操作指南
Python属于解释型语言,无需编译环节,你需要的自动执行脚本可以直接实现环境校验、代码运行的全流程,具体操作如下:
1. 保存Python代码
将你提供的示例代码保存为perfect_num_check.py文件,内容如下(已还原HTML转义字符):
# Python3 code to check if a given # number is perfect or not # Returns true if n is perfect def isPerfect( n ): # To store sum of divisors sum = 1 # Find all divisors and add them i = 2 while i * i <= n: if n % i == 0: sum = sum + i + n/i i += 1 # If sum of divisors is equal to # n, then n is a perfect number return (True if sum == n and n!=1 else False) # Driver program print("Below are all perfect numbers till 10000") n = 2 for n in range (10000): if isPerfect (n): print(n , " is a perfect number") # This code is contributed by "Sharad_Bhardwaj".
2. 编写Linux/macOS可用的Shell脚本(.sh文件)
创建名为run.sh的文件,写入以下内容:
#!/bin/bash # 检查Python3环境是否存在 if ! command -v python3 &> /dev/null then echo "错误:未检测到Python3环境,请先完成Python3安装后重试" exit 1 fi # 执行目标Python代码 python3 perfect_num_check.py
脚本使用方法
将perfect_num_check.py和run.sh放在同一目录下,终端执行以下命令赋予脚本执行权限后即可直接运行:
# 赋权只需执行一次 chmod +x run.sh # 运行脚本 ./run.sh
3. 编写Windows可用的一键运行脚本(.bat文件)
如果使用方是Windows系统,可创建run.bat文件,写入以下内容:
@echo off python --version >nul 2>&1 if %errorlevel% neq 0 ( echo 错误:未检测到Python环境,请先完成Python安装后重试 pause exit /b 1 ) python perfect_num_check.py pause
脚本使用方法
将perfect_num_check.py和run.bat放在同一目录下,直接双击run.bat即可自动执行代码。
补充说明
- 如果后续你的代码引入了第三方依赖,可以新增
requirements.txt文件记录依赖,在脚本中增加pip install -r requirements.txt逻辑即可实现自动安装依赖。 - 如果你需要打包为不需要Python环境也能运行的单文件,可以使用pyinstaller工具实现,常规分发场景使用上述脚本即可满足需求。
内容的提问来源于stack exchange,提问作者user12889057
相关产品推荐
相关产品推荐

