在shell脚本中运行的python脚本中无法运行转义序列

2024-05-15 05:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个需要运行python脚本的shell脚本。python脚本可以传递一个参数。在

python pgm32.py $args

但是,如果传递的参数有转义序列,或者我用引号括起来,python脚本将无法识别它。在

例如,假设args包含"Open drive"Open\ drive 然后是python脚本的sys.argv=['pgm32.py', '"Open', 'drive"']或{}。在

但是当我从命令行直接调用python脚本并传递一个参数,比如"Open drive"或{},则脚本的sys.arv=['pgm32.py', 'Open drive']

我如何解决这个问题?在


Tags: 命令行py脚本参数sysargsdriveopen
3条回答

其实很简单。引用shell命令中的参数:

$ python pgm32.py "$args"

你已经自己做了:

But when I call the python script directly from the command line, and pass an argument like "Open drive" or Open\ drive, the script's sys.arv=['pgm32.py', 'Open drive']

这是因为在这些行中,您保护了空间不受shell分词的影响;在其他示例中,您没有这样做。在

这起作用了:

eval python pgm32.py $args

有关Setting an argument with bash的详细信息 谢谢@Barmar。在

假设这是Bash,可以使用数组变量。在

declare -a args                      # Make args an array.
args=("Open Drive" -d output_dir)    # Assign three elements.
python pgm32.py "${args[@]}"         # Pass to pgm32.py as array.

相关问题 更多 >

    热门问题