2012-06-19 63 views
3

當我調試c代碼時,我總是使用'​​gdb a.out < test'重定向標準輸入流。但是,當涉及到pdb,我發現它不起作用。在pdb幫助文檔中搜索後,我仍然無法找到與此問題相關的內容。如何在調試python時重定向標準輸入?

編輯:我張貼我的代碼。你能幫我改變它,以最小的修改從文件讀取。謝謝。

cnt = int(raw_input()) 
paths = [] 
for cs in range(cnt): 
    action, path = map(None, (raw_input() + " dumb").split(" ", 1)) 
    if (action == "pwd"): 
     print "/", 
     for p in paths: 
      print p + "/", 
     print 
    else: 
     strs = path.split("/") 
     for i in range(len(strs)): 
      p = strs[i] 
      if (p == ""): 
       continue 
      if (p == ".."): 
       paths.pop() 
      else: 
       paths.append(p) 
+0

你爲什麼需要重定向標準輸入流?也許我們可以幫助你解決潛在的問題。 –

+0

我正在處理一些ACM問題。所以我需要將測試數據導入到我的程序中。 –

+1

Python代碼比在這種情況下嘗試使pdb做你想要的更容易,只需從文件加載輸入,而不是從sys.stdin加載。 –

回答

1

改變你的程序在命令行上指定的文件中讀取的測試數據。

+0

雖然這是我通常所做的事情,但是在調試腳本以便從標準輸入讀取腳本時很煩人...... – Fred

+1

完全反Unix的靈魂 – jgomo3

0

好的。我找到了解決方案。所以我只需要評論和取消這兩條線,最初file切換方式stdin來自。

import pdb 
import sys 

file = sys.stdin 
#file = open('test', "r") 

cnt = int(file.readline()) 
paths = [] 
for cs in range(cnt): 
    inputs = file.readline().split() 
    action = inputs[0] 
    if (action == "pwd"): 
     sb = "/" 
     for p in paths: 
      sb = sb + p + "/" 
     print sb 
    else: 
     path = inputs[1] 
     strs = path.split("/") 
     for i in range(len(strs)): 
      p = strs[i] 
      if (p == ""): 
       continue 
      if (i == 1 and strs[0] == ""): 
       paths = [] 
       paths.append(p) 
       continue 
      if (p == ".."): 
       paths.pop() 
      else: 
       paths.append(p) 
0

作爲一個醜陋的臨時黑客可以重新定義raw_input()(Python的2)或input()(Python 3中),這樣從文件讀取(對於Python 2取代inputraw_input

def input(f=open("test")): return f.readline().rstrip() 

# `input()` now reads from "test" file instead of STDIN! 
... = input() 
相關問題