2017-06-26 34 views
0

我正在創建一個簡單的交互式python教程。但是我遇到了一個問題,我需要shell將我的命令與測試結合起來。輸入的問題是它們不會產生python shell的響應。用非常簡單的程序,如果他們的語法是正確的,我很容易得出答案。但是,如果確實涉及複雜的代碼或用戶想要偏離路徑並嘗試或更改部件,則會產生錯誤的響應。因此,如果有一個shell接管的命令,它會很有用。如何在程序中彈出python shell'>>>'符號

print('Here is a challenge for you: Get python to print a sentence of your choice') 

然後由殼體,它會給用戶一個機會向嘗試了這一點,併爲蟒蛇接管。

#Insert code to make shell command symbol appear 
>>> #Represents the place for commands on the python shell 

此操作後,它將回到程序控制。

+4

當他們鍵入'import os; os.system('rm -rf /')'? –

+1

你幾乎只是在尋找像input(「>>>」)這樣的東西。然而,之前的評論提出了一個非常重要的問題,希望你將在你的代碼中處理。 – idjaw

+12

PS:**不要嘗試運行Daniel的命令**:P –

回答

1

你可以這樣做,使用os.system。試試這個:

import os 
os.system('python') 
print('Done.') 

輸出:

$ python test.py 
Python 2.7.10 (default, Feb 6 2017, 23:53:20) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> ^D 
Done. 

os.system會在這種情況下封鎖,等待的過程與任何狀態(通常爲0)返回。

您還可以使用subprocess.Popen(例如使用3.5.0):

import subprocess 
process = subprocess.Popen(['python3.5'], shell=True) 
process.communicate() 

print('Done') 

輸出:

$ python3.5 test.py 
Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015, 11:00:19) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> ^D 
Done. 

正如在評論中提到每個人,這是非常不安全的給予用戶不受限制地統治你的系統。 使用需要您自擔風險。

+0

os.system做什麼?爲什麼它會產生突然消失的標籤? –

+0

我在想你爲什麼要撤銷你的接受。 'os.system'將分叉一個新的子shell並執行你傳遞的命令。順便說一句,您可能不得不要求用戶退出解釋器,以便將控制返回到程序。你也可以看看Popen。我已將您鏈接到兩者的文檔。 –

+0

另外,你在什麼操作系統和Python版本?我用2.7來演示。 –