2010-04-09 36 views
15

Tôi muốn làm điều gì đó như:Có cách nào để làm cho python trở nên tương tác ở giữa tập lệnh không?

do lots of stuff to prepare a good environement 
become_interactive 
#wait for Ctrl-D 
automatically clean up 

Có thể với python Nếu không, bạn có thấy một cách khác để làm điều tương tự?

+3

Cảm ơn tất cả! Đối với hồ sơ, cách dễ nhất để sử dụng mô-đun mã để đạt được điều này là: mã nhập mã.interact (local = globals()) –

+2

Để nhận biến cục bộ vào không gian tên, bạn cần ' code.interact (local = dict (globals(), ** locals()) '. Lưu ý việc thêm' ** locals'. Tôi tự hỏi câu hỏi này và nhận xét của bạn là câu trả lời hay nhất tôi tìm thấy:) –

Trả lời

5

Với IPython v1.0, bạn chỉ có thể sử dụng

from IPython import embed 
embed() 

với nhiều tùy chọn hiển thị trong docs.

+0

Bạn có thể sử dụng nó ở bất cứ đâu và nó giữ nguyên phạm vi. –

-1

Bạn có thể gọi python bản thân:

import subprocess 

print "Hola" 

subprocess.call(["python"],shell=True) 

print "Adios" 
8

Module code sẽ cho phép bạn để bắt đầu một Python REPL.

5

Không chính xác điều bạn muốn nhưng python -i sẽ bắt đầu nhắc tương tác sau khi thực thi tập lệnh.

-i: kiểm tra tương tác sau khi chạy kịch bản, (cũng PYTHONINSPECT = x) và lực lượng nhắc nhở, thậm chí nếu stdin không xuất hiện như một thiết bị đầu cuối

$ python -i your-script.py 
Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03) 
... 
>>> 
10

Sử dụng cờ -i khi bạn bắt đầu Python và thiết lập một bộ xử lý atexit để chạy khi dọn dẹp.

script.py File:

import atexit 
def cleanup(): 
    print "Goodbye" 
atexit.register(cleanup) 
print "Hello" 

và sau đó bạn chỉ cần bắt đầu Python với cờ -i:

C:\temp>\python26\python -i script.py 
Hello 
>>> print "interactive" 
interactive 
>>> ^Z 

Goodbye 
6

Để xây dựng trên câu trả lời của IVA: embedding-a-shell, incoporating code và ipython.

def prompt(vars=None, message="welcome to the shell"): 
    #prompt_message = "Welcome! Useful: G is the graph, DB, C" 
    prompt_message = message 
    try: 
     from IPython.Shell import IPShellEmbed 
     ipshell = IPShellEmbed(argv=[''],banner=prompt_message,exit_msg="Goodbye") 
     return ipshell 
    except ImportError: 
     if vars is None: vars=globals() 
     import code 
     import rlcompleter 
     import readline 
     readline.parse_and_bind("tab: complete") 
     # calling this with globals ensures we can see the environment 
     print prompt_message 
     shell = code.InteractiveConsole(vars) 
     return shell.interact 

p = prompt() 
p() 
Các vấn đề liên quan