我想在 Windows Batch 腳本中使用多行 python 陳述句。
例如,我的 BAT 腳本是:
@echo off
echo "Executing Python Code..."
goto python_code
:python_code_back
echo "Executed Python Code!"
pause
exit()
:python_code
python -c print("""Python code running""")
goto python_code_back
python -c適用于單個陳述句。但是讓我嵌入的python代碼是:
import random
num = input("Enter Number: ")
num = int(num)
if num%2 == 0:
print("Even")
else:
print("Odd")
exit()
如何在不呼叫另一個 Python 腳本或制作臨時 Python 檔案的情況下將此Python 代碼嵌入到我的Windows 批處理腳本中?
我有一些選擇:
與分號一起使用
python -c:我如何打算像上面的 if 陳述句這樣的代碼?如果有辦法,人們可能仍然想要多行干凈的代碼,但我會很感激這個答案。我可以運行
python并找到一種向解釋器發送命令的方法嗎?也許使用子流程?Is there any way I can build a multi-line string that has the python code and then send it to the python interpreter or python command?
In bash we could use EOF to keep multi-lines clean. Is there any similar method to this in BAT? I think no because people have proposed many workarounds to this.
Can
'''(three single-quotes) or"""(three douuble-quotes) syntax be used that are specially interpreted by Batch? Like here?
uj5u.com熱心網友回復:
試試這樣:
0<0# : ^
'''
@echo off
echo batch code
python %~f0 %*
exit /b 0
'''
import random
import sys
def isOdd():
print("python code")
num = input("Enter Number: ")
num = int(num)
if num%2 == 0:
print("Even")
else:
print("Odd")
def printScriptName():
print(sys.modules['__main__'].__file__)
eval(sys.argv[1] '()')
exit()
示例用法:
call pythonEmbeddedInBatch.bat isOdd
call pythonEmbeddedInBatch.bat printScriptName
第一行將是 python 中的布爾運算式,但會批量重定向到空標簽。其余的批處理代碼將在多行 python 注釋中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/439567.html
