命令行参数传入脚本¶
传统方式¶
举例: (该程序自动执行paraview, 将 3D vtk data 在 y=0平面做切片, 然后再将 2D 数据保存为 csv 格式)
# pvpython path:
# /opt/software/ParaView-5.11.0-RC2-MPI-Linux-Python3.9-x86_64/bin/pvpython
# usage example:
# pvpython autoparaviewslice.py dump.04000.vtk dump.04000.y0slice.ynorm1.csv
import sys
import os
from paraview.simple import *
paraview.simple._DisableFirstRenderCameraReset()
# 默认路径,按需修改
vtkpath = r'./vtk3dcartesian/'
csvpath = r'./csv2dcartesian/'
# 检查命令行参数是否满足要求
if len(sys.argv) != 3:
print("Usage: pvpython autoparaviewslice.py vtkname csvname")
sys.exit(1)
# 从命令行参数获取 vtk 文件名和 csv 文件名
vtkname = sys.argv[1]
csvname = sys.argv[2]
# 构造完整的文件路径
vtkfile = os.path.join(vtkpath, vtkname)
csvfile = os.path.join(csvpath, csvname)
print("Reading VTK file:", vtkfile)
dumpvtk = LegacyVTKReader(registrationName=vtkname, FileNames=[vtkfile])
# 创建切片(slice)
slice1 = Slice(registrationName='Slice1', Input=dumpvtk)
slice1.SliceType = 'Plane'
slice1.HyperTreeGridSlicer = 'Plane'
slice1.SliceOffsetValues = [0.0]
# 设置切片平面的法向量
slice1.SliceType.Normal = [0.0, 1.0, 0.0]
# 保存切片数据为 CSV 文件
print("Saving CSV file:", csvfile)
SaveData(csvfile, proxy=slice1, PointDataArrays=[
'B', 'B0', 'B_2', 'J', 'J0', 'J_2',
'P', 'P0', 'PE', 'PE0', 'PE_2', 'P_2',
'V', 'V0', 'V_2', 'conc', 'conc_2',
'diff', 'n', 'n0', 'n_2', 'tele', 'tele_2',
'tion', 'tion_2'
], Precision=10)
使用 argparse 包 (复杂情况)¶
if __name__ == "__main__":
def parse_math_arg(value):
try:
# Safely evaluate mathematical expressions using eval, allowing only np.pi
# To prevent security risks, restrict the evaluation environment
return eval(value, {"__builtins__": None}, {"pi": np.pi})
except Exception as e:
# Raise an error if the mathematical expression is invalid
raise argparse.ArgumentTypeError("Invalid mathematical expression: {}".format(value))
# Create a command line parser
parser = argparse.ArgumentParser(description="Process command line options.")
# Add the --angle argument which can accept any mathematical expression
# The type=parse_math_arg uses a custom function to parse the input expression
# Default=0 provides a default value of 0
parser.add_argument('--angle', '-e', type=parse_math_arg, default=tor_angle, help='set tor_angle in radians, e.g., "pi/2", "3.14", or "pi*0.5"')
# Add the --clean argument, -c and --clean are equivalent
# action='store_true' means this is a boolean flag; if --clean or -c is specified, its value will be True
parser.add_argument('--clean', '-c', action='store_true', help='Clean the save_path folder')
# Add the --save_path argument for specifying the data save path
# type=str indicates that this argument should be parsed as a string
parser.add_argument('--save_path', '-p', type=str, default=save_path, help='Set the save_path to save data')
parser.add_argument('--single_dump_name', '-d', type=str, default=single_dump_name, help='Set the single_dump_name')
parser.add_argument('--save_all', '-sa', action='store_true', help='save all dumps in ./data/')
# Parse the command line input arguments
args = parser.parse_args()
# Retrieve the save path and angle value from the parsed arguments
save_path = args.save_path
tor_angle = args.angle
single_dump_name = args.single_dump_name
# If the clean operation is specified, execute the cleaning logic
if args.clean:
os.system("rm -rf "+save_path) # Safely delete the directory
os.system("mkdir "+save_path)
print("Folder %s has been cleaned successfully!" % save_path)
sys.exit(0)
if args.save_all:
dump_list = os.listdir('./data/')
print dump_list