我有2个脚本。一个是.bat,另一个是python。 python脚本由.bat文件触发。在执行时,首先我将使用命令行参数运行.bat但是我需要将参数读入python脚本。
我做错了什么?
我像这样调用批处理脚本:
C:>main.bat c:\temp\text1.txt
main.bat:
@ECHO off
set var1=%~1
call python_script.bat
echo "returned to main"
pause
python_script.bat:
python -x %0 %*
print var1 # Notworking
import sys
var1 = sys.argv ############ Also not working
with open(var1, 'r+') as f:
content = f.read()
f.seek(0)
f.trunca........
答案 0 :(得分:0)
我对bat和windows不太了解但是windows不支持使用bat文件中的命令行参数调用python脚本吗?如果是这样的话,不会有这样的工作吗?
这适用于Linux shell:
call_py.sh:
# do stuff with command line argument 1 here ($1) and pass it on to py
echo "I'm a shell script and i received this cmd line arg: " $1
# pass $1 on to python as a cmd line arg here
python some_script.py $1
echo "shell script still running after python script finished"
The other question I linked to向我们展示了如何从bat调用python(虽然我无法验证它)。难道你不能像我在call_py.sh中那样在py脚本的名称之后添加var1
吗?
# syntax might be wrong
start C:\python27\python.exe D:\py\some_script.py var1
some_script.py然后收到$ 1 / var1作为sys.argv[1]
some_script.py:
import sys
print "I'm a python script called " + sys.argv[0]
print "I received this cmd line arg from shell: " + sys.argv[1]
输出:
$ sh call_py.sh "VARIABLE_GIVEN_TO_SHELL_AND_PASSED_TO_PY"
I'm a shell script and i received this cmd line arg: VARIABLE_GIVEN_TO_SHELL_AND_PASSED_TO_PY
I'm a python script called some_script.py
I received this cmd line arg from shell VARIABLE_GIVEN_TO_SHELL_AND_PASSED_TO_PY
shell script still running after python script finished
这是否有效或者Windows比我想象的还要怪? :)
<强>更新强>
我启动了旧的恶意软件磁铁并尝试从命令行传递参数 - &gt;批处理脚本 - &gt;蟒蛇。我没有使用你的python -x %0 %*
语法似乎允许在批处理脚本中运行python代码,而只是编写一个单独的.py文件并从.bat文件中调用它。
这适用于Windows 7:
call_py.bat:
@ECHO off
set var1=%~1
echo Bat script called with cmdline arg: "%var1%"
echo Passing cmdline arg to python script
call C:\Python27\python.exe C:\Users\bob\Desktop\print_arg1.py %var1%
echo Bat again - continuing...
pause
print_arg1.py:
import sys
try:
print "Python says hi and received this cmdline arg: " + sys.argv[1]
except IndexError:
print "Python says hi but didn't receive any cmdline args :("
输出:
C:\Users\bob\Desktop>call_py.bat I_AM_A_CMDLINE_ARG
Bat script called with cmdline arg: "I_AM_A_CMDLINE_ARG"
Passing cmdline arg to python script
Python says hi and received this cmdline arg: I_AM_A_CMDLINE_ARG
Bat again - continuing...
Press any key to continue . . .