Python调用tcsh脚本报错:syntax error near unexpected token `$argv[1]`
问题分析与解决
错误根源
你用os.system执行命令时,默认是**系统默认shell(通常是bash)**来解析脚本,但你的run_power.cmd和vars.cmd都是tcsh语法,bash不兼容tcsh的语法规则,所以出现语法错误:
- bash不认识tcsh的
switch语句和$argv[1]参数写法 - bash的if语法格式和tcsh完全不同,解析不了
if ( $1 == "-help" ... ) exit 0这种写法
解决步骤
改用tcsh直接执行主脚本
不要用source(source会在当前bash环境下执行脚本,忽略shebang),直接调用tcsh解释器运行run_power.cmd,这样整个脚本都会在tcsh环境下执行,语法就能正确解析。
修改Python代码里的命令:final_power_cmd = f'/usr/sachin/bin/tcsh {path}/run_power.cmd -abc {abc} -test {test} >> {log_file} & ' print(final_power_cmd) os.system(final_power_cmd)修复
vars.cmd的字符串引号问题
你的vars.cmd第22行有嵌套引号错误:"t-sis2sis "24ww15"",内层引号会提前闭合字符串,导致后续语法混乱,改成转义引号或者用单引号包裹:set CMD_HELP = '\n Available User Controls: \n\t-abc con.abc" \n\t-scenarios "max_nom" \n\t-up_tag "24ww20" \n\t-top_autofixer_vars "t-sis2sis \"24ww15\"" \n\t-qp_version "15.25" \n\t-tests "t4," \n\t-test_script "t3" \n'或者把整个字符串用双引号包裹,内层用单引号:
set CMD_HELP = "\n Available User Controls: \n\t-abc con.abc\" \n\t-scenarios \"max_nom\" \n\t-up_tag \"24ww20\" \n\t-top_autofixer_vars \"t-sis2sis '24ww15'\" \n\t-qp_version \"15.25\" \n\t-tests \"t4,\" \n\t-test_script \"t3\" \n"
额外说明
脚本的shebang#!/usr/sachin/bin/tcsh只有在直接执行脚本(比如./run_power.cmd)时才会生效,用source执行时,shebang会被当作注释,当前shell会直接解析脚本内容,这是你之前报错的核心原因。
内容的提问来源于stack exchange,提问作者sachin
相关产品推荐
相关产品推荐

