2017-01-05 73 views
0

我創建了一個批處理文件來運行的序列文件,但我的Python文件需要在輸入(從打電話的raw_input),我試圖找出如何處理這種過度批處理文件。如何處理蟒蛇的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() 
+0

更改'raw_input()'爲'sys.argv [1]'。 – jordanm

+0

@jordanm我覺得OP要採取從標準輸入,而不是參數輸入。 –

+0

@YevhenKuzmovych不按他的'run.bat'例子。 – jordanm

回答

-1

the問題與python無關。到你的shell。據http://ss64.com/nt/syntax-redirection.html 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" 
+0

是啊所以你可以展示怎麼做 – teddybear123

+0

我已經略微改變了python腳本來打印環境變量。 呼應 「開發」 | run.bat C:\ Python27 \ python.exe myfile.py 進入環境(dev | qa | prod)或停止至STOP environment =「dev」 –

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