2013-05-18 64 views
2

美好的一天!我正在嘗試實現一個測試知識的模塊。用戶被賦予了任務,他編寫了正在服務器上發送和執行的決定。下面的問題。有存儲在文件中的原始數據。示例 - a = 5 b = 7 存儲在字符串中的自定義解決方案。示例如何將字符串轉換爲所需的形式?

s = a * b 
p = a + b 
print s,p 

現在它全部寫入單獨的文件中作爲字符串。

'a = 5\n', 'b = 7', u's = a * b\r\np = a + b\r\nprint s,p' 

如何做到這一點,以便使用的代碼可以執行。會是這樣的。

a = 5 
b = 7 
s = a * b 
p = a + b 
print s,p 

這裏是我的函數來創建一個解決方案,並在必要時執行它。

def create_decision(user_decision, conditions): 
    f1 = open('temp_decision.py', 'w') 
    f = open(conditions, 'r+') 
    contents = f.readlines() 
    contents.append(user_decision) 
    f1.write(str(contents)) 
    f1.close() 
    output = [] 
    child_stdin, child_stdout, child_stderr = os.popen3("python temp_decision.py") 
    output = child_stdout.read() 
    return output 

或告訴我我做錯了什麼?謝謝!

回答

1

你並不需要創建一個臨時文件,你可以簡單地使用exec。然後create_decision看起來如此:

一個

def create_decision(user_decision, conditions): 
    f = open(conditions, 'r+') 
    contents = f.readlines() 
    contents.append(user_decision) 
    # join list entries with a newline between and return result as string 
    output = eval('\n'.join(contents)) 
    return output 

import sys 
import StringIO 
import contextlib 

@contextlib.contextmanager 
def stdoutIO(stdout=None): 
    old = sys.stdout 
    if stdout is None: 
     stdout = StringIO.StringIO() 
    sys.stdout = stdout 
    yield stdout 
    sys.stdout = old 

def create_decision(user_decision, conditions): 
    f = open(conditions, 'r+') 
    contents = f.readlines() 
    contents.append(user_decision) 
    with stdoutIO() as output: 
     #exec('\n'.join(contents)) # Python 3 
     exec '\n'.join(contents) # Python 2 
    return output.getvalue() 

您還應該使用str.join()使一個串出的條件之列。否則,你不能將它寫入文件或執行它(我已經在上面的函數中完成了這一點)。

編輯:沒有在我的代碼中的錯誤(exec不返回任何東西),所以我加入eval的方法(但不會有打印工作,因爲它計算並返回結果一個表達,更多信息here)。第二種方法捕獲printstdoutIO的輸出來自其他問題/答案(here)。此方法返回打印輸出,但有點複雜。

+0

我不明白是什麼問題。開始您的示例後,在字母「c」上顯示以下錯誤。 Python v.2.7.5'output = exec('\ n'.join(contents))SyntaxError:invalid syntax' – aphex

+0

我的代碼是針對Python 3的。現在我已將它更改爲Python 2(python 3行被註釋掉) – TobiMarg

+0

謝謝你,但它仍然不起作用。顯示相同的錯誤。 我啓動它,在pyton3上,但結果沒有寫入變量輸出並返回None – aphex

0

可以執行一個字符串,像這樣:exec("code")

+0

爲防萬一使用python 2.x,這將是'exec「代碼」'。 – SethMMorton

相關問題