如何嵌入批处理脚本蟒蛇code [英] How to embed python code in batch script

查看:170
本文介绍了如何嵌入批处理脚本蟒蛇code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中,我们可以:

In bash, we can:

python - << EOF
import os
print 'hello'
EOF

嵌入蟒蛇code片段在bash脚本。

to embed python code snippet in bash script.

而在Windows批次,这并不工作 - 虽然我仍然可以使用Python -c但是这需要我collpase我的code成一条线,这是我尽量避免

But in Windows batch, this doesn't work - although I can still use python -c but that requires me to collpase my code into one line, which is something I try to avoid.

有没有办法在批处理脚本来实现这一目标?

Is there a way to achieve this in batch script?

感谢。

推荐答案

您可以使用混合工艺。

You could use a hybrid technic.

1>2# : ^
'''
@echo off
echo normal 
echo batch code
echo Switch to python
python "%~f0"
exit /b
rem ^
'''
print "This is Python code"

批code是一个多行字符串'''所以这是蟒蛇不可见的。结果
批处理解析器没有看到蟒蛇code,因为它以前退出。

The batch code is in a multiline string ''' so this is invisible for python.
The batch parser doesn't see the python code, as it exits before.

第一行是关键。结果
它是有效的批次为也为蟒蛇!结果
在Python这只是一个毫无意义的比较 1&GT; 2 无输出,该行的其余部分是注释的

The first line is the key.
It is valid for batch as also for python!
In python it's only a senseless compare 1>2 without output, the rest of the line is a comment by the #.

有关批次 1&GT; 2#是流 1 到文件重定向 2#。结果
命令的是一个冒号这表示一个标签和标记线从不打印结果。
那么最后插入符只需追加下一行的标签行,这样一批不看'''行。

For batch 1>2# is a redirection of stream 1 to the file 2#.
The command is a colon : this indicates a label and labeled lines are never printed.
Then the last caret simply append the next line to the label line, so batch doesn't see the ''' line.

这篇关于如何嵌入批处理脚本蟒蛇code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆