如何在批处理文件中处理python raw_input()

时间:2017-01-05 21:21:09

标签: python batch-file

我创建了一个批处理文件来按顺序运行文件,但是我的python文件接受了一个输入(来自调用raw_input),我试图弄清楚如何在批处理文件中处理它。

run.bat

执行.py文件后,程序不会进入下一行,为简洁起见,我只是显示了必要的命令

cd C:\Users\myname\Desktop
python myfile.py
stop

myfile.py

print ("Enter environment (dev | qa | prod) or stop to STOP")
environment = raw_input()   

2 个答案:

答案 0 :(得分:0)

这是一个解决方案。

获取myfile.py文件,并将其更改为以下内容:

import sys

def main(arg = None):
    # Put all of your original myfile.py code here
    # You could also use raw_input for a fallback, if no arg is provided:
    if arg is None:
        arg = raw_input()
    # Keep going with the rest of your script

# if __name__ == "__main__" ensures this code doesn't run on import statements
if __name__ == "__main__":
    #arg = sys.argv[1] allows you to run this myfile.py directly 1 time, with the first command line paramater, if you want

    if len(sys.argv) > 0:
        arg = sys.argv[1]
    else:
        arg = None

    main(arg)

然后创建另一个python文件,名为wrapper.py:

#importing myfile here allows you to use it has its own self contained module
import sys, myfile

# this loop loops through the command line params starting at index 1 (index 0 is the name of the script itself)
for arg in sys.argv[1 : ]:

    myfile.main(arg)

然后在命令行中,您只需输入:

python wrapper.py dev qa prod

你也可以在run.bat文件中放上上面一行代码,看看如下:

cd C:\Users\myname\Desktop
python wrapper.py dev qa prod
stop

答案 1 :(得分:-1)

问题与python无关。到你的shell。根据{{​​3}} cmd.exe使用与unix shell相同的语法(cmd1 | cmd2),因此使用命令调用时,bat文件应该可以正常工作,这会将文件内容发送到标准输出。

编辑:添加了示例

echo "dev" | run.bat
C:\Python27\python.exe myfile.py
Enter environment (dev | qa | prod) or stop to STOP
environment="dev"