2016-03-20 28 views
5

IPython'un alma hatalarını varsayılan olarak nasıl değiştirdiğini değiştirmek istiyorum. IPython kabuğunda bir şey prototiplediğimde, genellikle ilk önce os, re veya ne gerekiyorsa almayı unuturum.IPython İthalatı Yaparım Ne demek

In [1]: os.path.exists("~/myfile.txt") 
--------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 
<ipython-input-1-0ffb6014a804> in <module>() 
----> 1 os.path.exists("~/myfile.txt") 

NameError: name 'os' is not defined 

In [2]: import os 

In [3]: os.path.exists("~/myfile.txt") 
Out[3]: False 

Tabii, bu benim suçum anlamda, kılan bir komut dosyası veya gerçek programda ama doğrusu bu olur kabuğunda, kötü alışkanlıkları ve emin olması için verilmiştir: İlk birkaç tablolar çoğu zaman bu deseni takip IPython, kullanmaya çalıştığım öğeyi almak için numaralı telefonu kullanarak en az numaralı DWIM ilkesini uygular. Bu vanilyalı ipython ile mümkün değilse

In [1]: os.path.exists("~/myfile.txt") 
--------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 
<ipython-input-1-0ffb6014a804> in <module>() 
----> 1 os.path.exists("~/myfile.txt") 

NameError: name 'os' is not defined 

Catching this for you and trying to import "os" … success! 
Retrying … 
--------------------------------------------------------------------------- 
Out[1]: False 

, ben bu işi yapmak için ne olurdu? wrapper kernel en kolay yol mu? Ya da bu, bir büyü komutuyla doğrudan merkezde uygulanmalı mı?

Not: Bu, birinin önceden tanımlı modülleri her zaman yüklemek istediği those kind of question'dan farklıdır. Yapmıyorum. Üzerinde çalıştığım olacak bilmiyorum, ben herşeyi yüklemek istemiyorum (ne de ben güncellenmiş herşeyi listesini saklamak istiyorsunuz Cuz

cevap

10

NOT:. Bu artık on Github muhafaza ediliyor. oradan script son sürümünü indirin!

Ben set_custom_exc aracılığıyla işleme ipython en istisna bağlanan bir komut dosyası geliştirdi. bir NameError varsa, bu kullanmaya çalıştı ve sonra ne modül bulmak için bir normal ifade kullanır Daha sonra tekrar aramayı denediğiniz fonksiyonu çalıştırırsınız. İşte kod:

import sys, IPython, colorama # <-- colorama must be "pip install"-ed 

colorama.init() 

def custom_exc(shell, etype, evalue, tb, tb_offset=None): 
    pre = colorama.Fore.CYAN + colorama.Style.BRIGHT + "AutoImport: " + colorama.Style.NORMAL + colorama.Fore.WHITE 
    if etype == NameError: 
     shell.showtraceback((etype, evalue, tb), tb_offset) # Show the normal traceback 
     import re 
     try: 
      # Get the name of the module you tried to import 
      results = re.match("name '(.*)' is not defined", str(evalue)) 
      name = results.group(1) 

      try: 
       __import__(name) 
      except: 
       print(pre + "{} isn't a module".format(name)) 
       return 

      # Import the module 
      IPython.get_ipython().run_code("import {}".format(name)) 
      print(pre + "Imported referenced module \"{}\", will retry".format(name)) 
     except Exception as e: 
      print(pre + "Attempted to import \"{}\" but an exception occured".format(name)) 

     try: 
      # Run the failed line again 
      res = IPython.get_ipython().run_cell(list(get_ipython().history_manager.get_range())[-1][-1]) 
     except Exception as e: 
      print(pre + "Another exception occured while retrying") 
      shell.showtraceback((type(e), e, None), None) 
    else: 
     shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset) 

# Bind the function we created to IPython's exception handler 
IPython.get_ipython().set_custom_exc((Exception,), custom_exc) 

bu dosyaya yoluna PYTHONSTARTUP denilen bir ortam değişkeni sonra bir yere kaydedip tarafından ipython istemi başlattığınızda otomatik olarak bu kaçabilirler. Eğer işletim bağlı olarak farklı ortam değişkenlerini kurmak (yolları değiştirmek için unutmayın):

  • Windows'u: Komut isteminde setx PYTHONSTARTUP C:\startup.py
  • Mac/Linux (bash): senin ~/.bashrc

içine export PYTHONSTARTUP=$HOME/startup.py koy

Demo

+0

_Currently, bu komut infi: Burada eylem script bir demo bazı hatalar üzerine nite-döngüler - NameError'da içe aktarma sonuçları ve temizleme rutini aynı içeriyorsa ... - zaten ne olduğunu biliyorsunuz. Varlamaya çalıştığınız modülün olup olmadığını kontrol etmeniz gerekiyor. –

+0

@Rogalski Bunu nasıl yaparım? Pip'in bunu yapmak için yöntemleri olduğunu biliyorum ama birileri kendi yerel makinelerinde bir şey ithal ediyor olabilir. –

+0

Çalıştır: 'try: importError hariç her şeyi içe aktar: oops_failed_to_import_handle_it()'? –