everydayminder

learn something everyday

Archive for April 2009

calInThread vs callFromThread

leave a comment »

twistedmatrix에서 callInThread()와 callFromThread()는 어떻게 다른 것일까?
무심코, 코드에서 callInThread()를 썼는데, 그 차이를 궁금해 하다가 문서 및 소스를 찾아보게
되었다.

1. The Twisted Documentation 보기
우선 살펴본, The Twisted Documentation에서는 callFromThread()는 thread-safe하지 않은 메소드를 thread-safe하게 실행시킬 때 사용한다고 한다. 다른 설명으로는, thread-safe하지 않은 메소드를 메인 이벤트 루프에서 실행되도록 스케쥴한다고 한다.

from twisted.internet import reactor

def notThreadSafe(x):
“”” do something that isn’t thread-safe “””
# …

def threadSafeScheduler():
“”” Run in thread-safe manner.”””
reactor.callFromThread(noThreadSafe, 3)

반면, callInThread()는 thread상에서 메소드들을 호출하고 싶을 때 사용하며, 이 메소드들이 thread pool에 의해 queue처리 되면서 실행되도록 한다고 한다.

from twisted.internet import reactor

def aSillyBlockingMethod(x):
   import time
   time.sleep(2)
   print x

# run method in thread
reactor.callInThread(aSillyBlockiingMethod, “2 seconds have passed”)

이것을 본 소감은..

1. “그게 뭔데~ 어쩌라고~”
2. no thread-safe 함수는 callFromThread()를 쓰고, safe 함수는 callInThread()를 쓰는 것인가?
3. blocking이 내부적으로 발생할 수 있는 함수는 callInThread()를 쓰는 것인가?

등 용도가 명확하지 않았다.





2. API 찾아보기
그래서, twisted API로부터, callInThread()와 callFromThread()에 대한 설명을 참고하게 되었다.
아래는 각각 callFromThread()와 callInThread()에 대한 API 설명이다.

[callFromThread()]

Run the callable object in a separate thread.

[callInThread()]


Cause a function to be executed by the reactor thread.


Use this method when you want to run a function in the reactor’s thread from another thread. Calling callFromThread should wake up the main thread (where reactor.run() is executing) and run the given callable in that thread.

Obviously, the callable must be thread safe. (If you want to call a function in the next mainloop iteration, but you’re in the same thread, use callLater with a delay of 0.)

위의 설명을 따른다면, callFromThread()는 별도의 thread를 띄워서 실행시켜 준다는 것이나,
callInThread()는 reactor의 내부 thread에 위탁한다는 것으로 보인다.




3. 다른 참고 문서에서는..
한편, 다른 문서에서는 각 메소드의 사용 용도에 차이를 다음과 같이 두었다.

def threadDoSomething(a, b):
   d = defer.Deferred()
   def func():
      result = doSomething(a, b)
      reactor.callFromThread(d.callback, result)
   t = threading.Thread(target = func)
   t.start()
   return d

def threadDoSomethingNew(a, b):
   d = defer.Deferred()
   def func():
      result = doSomething(a, b)
      reactor.callFromThread(d.callback, result)
   reactor.callInThread(func)
   return d


위의 사용예와 해당 문서의 설명에 따르면, reactor.callFromThread()는 twisted 중, 유일하게 thread-safe 메소드이며, reactor thread의 내부에서 주어진 함수를 실행시킨다. 첫번째 함수는 정상동작하나, 반복적으로 호출하면 새로운 thread를 계속 생성하므로 시스템에 부하를 주므로, 두번째 함수와 같이 사용하는 것이 효과적이다.

결과적으로, callInThread()는  twisted를 사용하지 않는 방식에서 threading.Thread().start() 대신에 사용하면 된다는 것이다.

from twisted.internet import reactor

c = 1
# this triial example function is
# not thread-safe
def increment(x):
   global c
   c = c + x

def threadTask():
   # run non-threadsafe function
   # in thread-safe way — increment(7)
   # will be called in event loop thread
   reactor.callFromThread(increment, 7)

# add a number of tasks to thread pool
for i in range(10):
   reactor.callInThread(threadTask)

출처 : Network Programming for the Rest of Us, Glyph Lefkowitz, http://www.twistedmatrix.com/users/glyph


위의 예 대로라면, thread를 launch 시킬 때는 callInThread()를 쓰고, callFromThread()를 사용하여 thread-safe하게 동작하도록 해준다는 것이다.

그래도, 미심쩍은 면은 있다!!

4. 소스에서는?
한편, 다른 문서에서는 각 메소드의 사용 용도에 차이를 다음과 같이 두었다.

[callFromThread]

추적해보니, base.py에 정의되어 있음.

def callFromThread(self, f, *args, **kw):
    “””See twisted.internet.interfaces.IReactorThreads.callFromThread.
    “””
    assert callable(f), “%s is not callable” % (f,)
    # lists are thread-safe in CPython, but not in Jython
    # this is probably a bug in Jython, but until fixed this code
    # won’t work in Jython.
    self.threadCallQueue.append((f, args, kw))
    self.wakeUp()

threadCallQueue는 ReactorBse에 선언된 변수로서, list이다. callFromThread()가 호출될 때마다
내부의 threadCallQueue 리스트에 추가되고, runUntilCurrent()라는 내부 메소드가 실행 되면 wakeup 해서, queue 내부의 함수를 순차적으로 시행하고, dequeue시킨다.

[callInThread]
추적해보니, base.py 및 threadpool.py에 정의되어 있음.

def callInThread(self, _callable, *args, **kwargs):
    “””See twisted.internet.interfaces.IReactorThreads.callInThread.
    “””
    if self.threadpool is None:
    self._initThreadPool()
    self.threadpool.callInThread(_callable, *args, **kwargs)

def callInThread(self, func, *args, **kw):
    if self.joined:
    return
    ctx = context.theContextTracker.currentContext().contexts[-1]
    o = (ctx, func, args, kw)
    self.q.put(o)
    if self.started:
        self._startSomeWorkers()


위의 코드에서 보는 바와 같이, callInThread를 호출하면, 내부에 정의한 Queue.Queue 객체에
함수를 넣고, thread pool에 정의된 수에 따라 동작시킨다. 내부적으로 threading.Thread()를
미리 실행시켜서 queue로 보관하고 있다.

결과적으로, callFromThread를 사용하면, 내부의 이벤트 루프에 넣어서 실행되도록 하고, callInThread를 사용하면, 내부에 생성해 놓은 thread pool로부터 실행하는 것이다라는 설명이 맞다는 뜻 되겠다~

따라서, 새로 시작하는 thread를 callInThread에 넣어서 시작시키고, 내부적으로 callFromThread를 타도록 시키는 게 맞겠다. 문서에 나와 있는 바와 같이, twisted API는 callFromThread를 통해서 호출하라고 한 것도 같은 맥락으로 보인다.

Written by everydayminder

April 27, 2009 at 08:40

남의 눈에 띄지 않으려 하다

leave a comment »

try to keep a low profile

그녀가 남의 눈에 띄지 않으려고 했던 것 같아.
I guess she was trying to keep a low profile.

Written by everydayminder

April 22, 2009 at 23:09

Posted in Life/English

Tagged with ,

Recommended Books for S/W & H/W Developers (@Intel)

leave a comment »

Recommended Reading List



  1. Books for H/W Developers

    1. I/O Interconnection Technologies

      1. Designing High-Speed Interconnect Circuits/Dennis Miller
      2. Jitter, Noise, and Signal Integrity at High-Speed/Mike Peng Li
      3. Timing Analysis and Simulation for Signal Integrity Engineers/Greg Edlund
      4. High-Speed Signal Propagation: Advanced Black Magic/Howard W. Johnson
      5. Introduction to PCI Express*/Adam Wilen, Justin Schade, and Ron Thornburg
      6. PCI Express* Electrical Interconnect Design/Dave Coleman, Scott Gardiner, Mohammad Kolbehdari and Stephen Peters
      7. PCI Express* System Architecture/Mindshare Inc, Ravi Budruk, Don Anderson, Tom Shanley
      8. USB Design by Example, Second Edition/John Hyde
      9. InfiniBand Architecture: Development and Deployment/William T. Futral

    2. Power and Thermal Management

      1. Thermal Guidelines For Data Processing Environments/TC9.9 MISSION CRITICAL FACILITIES
      2. Building the Power Efficient PC/Jerzy Kolinski, Ram Chary, Andrew Henroid and Barry Press
      3. Datacom Equipment Power Trends and Cooling Applications/Refrigerating and Air Conditioning Engineers American Society of Heating
      4. Hot Air Rises and Heat Sinks: Everything You Know About Cooling Electronics Is Wrong/Tony Kordyban
      5. Thermal Guidelines For Data Processing Environments/TC9.9 MISSION CRITICAL FACILITIES
      6. Power Management in Mobile Devices/Findlay Shearer
      7. Thermal Management Handbook: For Electronic Assemblies/Jerry E. Sergent, Al Krum

    3. Storage Technologies

      1. Serial ATA Storage Architecture and Applications/Knut Grimsrud, Hubbert Smith
      2. Storage Network Performance Analysis/Huseyin Simitci
      3. Storage Networking Fundamentals/Marc Farley

    4. Wireless Technologies

      1. 802.11 Wireless Networks: The Definitive Guide/Matthew Gast
      2. Advanced Wireless Communications: 4G Technologies/Savo G. Glisic
      3. Implementing 802.11, 802.16, and 802.20 Wireless Networks/Ron Olexa
      4. Mobile Web Services/Ariel Pashtan
      5. Multi-Platform Wireless Web Applications: Cracking the Code/Dreamtech Software Team
      6. Real 802.11 Security: WiFi Protected Access and 802.11i/Jon Edney, William A. Arbaugh
      7. Ultra-wideband Radio Technology/Kazimierz Siwiak, Debra McKeown
      8. Ultra-wideband Wireless Communications and Networks/Xuemin Shen, Mohsen Guizani
      9. WiMAX Handbook/Frank Ohrtman
      10. WiMax Operator’s Manual: Building 802.16 Wireless Networks/Daniel Sweeney
      11. Fundamentals of WiMAX: Understanding Broadband Wireless Networking/Jeffrey G. Andrews, Arunabha Ghosh, Rias Muhamed
      12. Wireless Hacks, 2nd Edition/Rob Flickenger, Roger Weeks

  2. Books for S/W Developers

    1. S/W Threading for Many Core Architectures

      1. Computer Architecture: A Quantitative Approach, Third Edition/John L. Hennessy and David Patterson
      2. Concurrent Programming in Java*: Design Principles and Patterns, Second Edition/Douglas Lea
      3. Multi-Core Programming/Shameem Akhter, Jason Roberts
      4. Multithreading Applications in Win32: The Complete Guide to Threads/Jim Beveridge, Robert Wiener
      5. Parallel Programming in C with MPI and OpenMP/Michael J. Quinn
      6. Parallel Programming in OpenMP/Rohit Chandra, et al
      7. Using OpenMP: Portable Shared Memory Parallel Programming/Barbara Chapman, Gabriele Jost, Ruud van der Pas
      8. Parallel Programming with MPI/Peter Pacheco
      9. Patterns for Parallel Programming/Timothy G. Mattson, Beverly A. Sanders, Berna L. Massingill
      10. Programming with Hyper-Threading Technology/Andrew Binstock, Richard Gerber
      11. Programming with POSIX Threads/David R. Butenhof
      12. The Software Optimization Cookbook, Second Edition/Richard Gerber, Aart J.C. Bik, et al
      13. Optimizing Applications for Multi-Core Processors/Stewart Taylor
      14. Intel Threading Building Blocks: Outfitting C++ for Multi-core Processor Parallelism/James Reinders
      15. Java Concurrency in Practice/Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea
      16. Threads Primer: A Guide to Multithreaded Programming/Bil Lewis, Daniel J. Berg

    2. Software Development

      1. Beyond BIOS/Vincent Zimmer, Michael Rothman, and Robert Hale
      2. Breaking Through the BIOS Barrier/Adrian Wong
      3. C Interfaces and Implementations: Techniques for Creating Reusable Software/David R. Hanson
      4. Code Complete, Second Edition/Steve McConnell
      5. IA64 Linux Kernel: Design and Implementation/David Mosberger, Stephane Eranian
      6. Intel® Integrated Performance Primitives/Stewart Taylor
      7. Mac OS X* Internals: A Systems Approach/Amit Singh
      8. Microsoft Windows* Internals, Fourth Edition/Mark E. Russinovich, David A. Solomon
      9. The C Programming Language, Second Edition/Brian W. Kernighan, Dennis Ritchie
      10. The Common Language Infrastructure Annotated Standard/Jim Miller, Susann Ragsdale
      11. The Software Vectorization Handbook/Aart J.C. Bik
      12. UPnP† Design by Example/Michael Jeronimo, Jack Weast
      13. VTune™ Performance Analyzer Essentials/James Reinders
      14. Windows System Programming, Third Edition/Johnson M. Hart

    3. High-Performance Computing

      1. Software Optimization for High-Performance Computing: Creating Faster Applications/Isom Crawford, Kevin Wadleigh
      2. Grid Computing: The New Frontier of High-Performance Computing (Volume 14)/Lucio Grandinetti
      3. High-Performance Cluster Computing: Architectures and Systems/Rajkumar Buyya
      4. High-Performance Computing Systems and Applications/Robert D. Kent, Todd W. Sands
      5. High-Performance Linux Clusters with OSCAR, Rocks, OpenMosix and MPI/Joseph D Sloan
      6. High-Performance Computing: Paradigm and Infrastructure/Laurence T. Yang, Minyi Guo
      7. Principles of Transaction Processing/Philip A. Bernstein, Eric Newcomer
      8. Transaction Processing: Concepts and Techniques/Jim Gray, Andreas Reuter
      9. Using MPI2/William Gropp, et al

    4. Graphics and Gaming Technologies

      1. OpenGL® Programming Guide: The Official Guide to Learning OpenGL®, Version 2.1, Sixth Edition/Dave hreiner, Mason Woo, Jackie Neider, Tom Davis
      2. OpenGL® Shading Language, Second Edition/Randi Rost
      3. Game Programming Gems 6/Mike Dickheiser
      4. Game Programming Gems 7/Scott Jacobs
      5. ShaderX5: Advanced Rendering Techniques/Wolfgang Engel
      6. OpenGL® Library, Fourth Edition/Dave Shreiner, Randi Rost

    5. Digital Home Technologies

      1. Audio in the 21st Century/Scott Janus
      2. Designing for Product Sound Quality/Richard H. Lyon
      3. Developing User Interfaces: Ensuring Usability Through Product & Process/Deborah Hix, H. Rex Hartson
      4. Digital Video and HDTV Algorithms and Interfaces/Charles Poynton
      5. Fundamentals of Audio and Video Programming for Games/Peter Turcan, Mike Wasson
      6. High-Definition Audio for the Digital Home/David Roach, Scott Janus, and Wayne Jones
      7. Power Line Communications and Its Applications (ISPLC), 2006 IEEE International Symposium IEEE Press
      8. Psychoacoustics: Facts and Models, Third Edition/Hugo Fastl and Eberhard Zwicker
      9. Usability in Practice: How Companies Develop User-Friendly Products/Michael E. Wiklund

    6. IT Strategic Considerations

      1. Managing Information Technology for Business Value/Martin Curley
      2. Measuring the Business Value of Information Technology/David Sward
      3. Managing IT Innovation for Business Value/Esther Baldwin and Martin Curley

    7. Data Center Technologies

      1. Advanced Server Virtualization: VMware and Microsoft Platforms in the Virtual Data Center/David Marshall, Wade A. Reynolds, Dave McCrory
      2. Definitive XML Schema/Priscilla Walmsley
      3. Service Oriented Architecture (SOA): Concepts, Technology, and Design/Thomas Erl
      4. Service Oriented Architecture Demystified/Girish Juneja, Blake Dournaee, Joe Natoli, and Steve Birkel
      5. Service Oriented Architecture (SOA): A Planning and Implementation Guide for Business and Technology/Eric A. Marks, Michael Bell
      6. SOA Principles of Service Design/Thomas Erl
      7. Applied Virtualization Technology/Sean Campbell and Michael Jeronimo
      8. Design Considerations for Datacom Equipment Centers/Refrigerating and Air Conditioning Engineers American Society of Heating
      9. Internet Communications Using SIP: Delivering VoIP and Multimedia Services with Session Initiation Protocol/Henry Sinnreich, Alan B. Johnston
      10. IPTV Crash Course (Publish date Nov 2006)/Joseph M. Weber, Tom Newberry
      11. Itanium® Architecture for Programmers: Understanding 64-Bit Processors and EPIC Principles/James S. Evans, Gregory L. Trimper
      12. Patterns of Enterprise Application Architecture/Martin Fowler
      13. Scientific Computing on Itanium®-based Systems/Marius Cornea, Ping Tak Peter Tang, John Harrison
      14. Itanium® Architecture for Software Developers/Walter Triebel
      15. Programming Itanium®-based Systems/Walter Triebel, Joseph Bissell, Rick Booth
      16. Virtual Machines: Versatile Platforms for Systems and Processes/Jim Smith, Ravi Nair
      17. Server Consolidation With the IBM Eserver Xseries* 440 and Vmware Esx Server*/Steve Russell, Keith Olsen, Gabriel Sallah, Chandra Seetharaman, David Watts
      18. Switching to VoIP/Theodore Wallingford

    8. Business Client Technologies

      1. Building Applications with the Linux* Standard Base/Linux Standard Base Team
      2. Flash Memory Technologies: A Comprehensive Guide to Understanding and Using Flash Memory Devices/Joseph E. Brewer
      3. Virtualization: From the Desktop to the Enterprise/Chris Wolf, Erick M. Halter
      4. Practical Guide to Trusted Computing/David Challener, Kent Yoder, Ryan Catherman, David Safford, Leendert Van Doorn
      5. Cisco Network Admission Control, Volume I: NAC Framework Architecture and Design/Denise Helfrich, Lou Ronnau , Jason Frazier, Paul Forbes
      6. Windows Server* 2008 Networking and Network Access Protection (NAP)/Joseph Davies and Tony Northrup
      7. The Intel Safer Computing Initiative/David Grawrock

Written by everydayminder

April 15, 2009 at 08:36

Posted in Life/Memo

Tagged with , ,

Windows에서 DNS cache 지우기

leave a comment »

windows 자체도 DNS caching을 하므로,
콘솔에서 다음과 같이 입력한다.

ipconfig /flushdns

Written by everydayminder

April 14, 2009 at 00:43

Posted in TIPs

They were meant for each other.

leave a comment »

그 사람들은 천생연분이다.

Written by everydayminder

April 9, 2009 at 23:40

Posted in Life/English

Books that I want to read sometime

leave a comment »

from :
http://agile.dzone.com/news/top-50-new-software

1 Dreaming in Code: Two Dozen Programmers, Three Years, 4,732 Bugs, and One Quest for Transcendent Software/Scott Rosenberg/ 26-1-2007
2 Clean Code: A Handbook of Agile Software Craftsmanship/Robert C. Martin/ 11-8-2008
3 Pragmatic Thinking and Learning: Refactor Your Wetware/Andy Hunt/ 15-8-2008
4 Managing Humans: Biting and Humorous Tales of a Software Engineering Manager/Michael Lopp/ 12-6-2007
5 Beautiful Code: Leading Programmers Explain How They Think/Andy Oram, Greg Wilson/ 26-6-2007
6 SOA Principles of Service Design/Thomas/ Erl 28-7-2007
7 The Productive Programmer/Neal Ford/ 3-7-2008
8 Smart and Gets Things Done: Joel Spolsky’s Concise Guide to Finding the Best Technical Talent/Joel Spolsky/ 31-5-2007
9 Making Things Happen: Mastering Project Management/Scott Berkun/ 25-3-2008
10 Release It!: Design and Deploy Production-Ready Software/Michael Nygard/ 30-3-2007
11 The Art of Agile Development/James Shore, Shane Warden/ 26-10-2007
12 Service-Oriented Modeling: Service Analysis, Design, and Architecture/Michael Bell/ 25-2-2008
13 Scaling Software Agility: Best Practices for Large Enterprises/Dean Leffingwell/ 8-3-2007
14 The Annotated Turing: A Guided Tour Through Alan Turing’s Historic Paper on Computability and the Turing Machine/Charles Petzold/ 16-6-2008
15 Sketching User Experiences: Getting the Design Right and the Right Design/Bill Buxton/ 11-4-2007
16 Continuous Integration: Improving Software Quality and Reducing Risk/Paul Duvall, Steve Matyas, Andrew Glover/ 9-7-2007
17 SOA Design Patterns/Thomas Erl/ 23-10-2008
18 The Developer’s Guide to Debugging/Thorsten Grotker, Ulrich Holtmann, Holger Keding, Markus Wloka/ 11-8-2008
19 Agile Adoption Patterns: A Roadmap to Organizational Success/Amr Elssamadisy/ 7-7-2008
20 Manage It!: Your Guide to Modern, Pragmatic Project Management/Johanna Rothman/ 7-6-2007
21 The Principles of Project Management/Meri Williams/ 13-3-2008
22 Introduction to Information Retrieval/Christopher D. Manning, Prabhakar Raghavan, Hinrich Schutze/ 7-7-2008
23 Head First Software Development/Dan Pilone, Russ Miles/ 11-1-2007
24 Web Service Contract Design and Versioning for SOA/Thomas Erl, Anish Karmarkar, Priscilla Walmsley/ 21-9-2008
25 The Art of Multiprocessor Programming/Maurice Herlihy, Nir Shavit/ 29-2-2008
26 Scaling Lean & Agile Development: Thinking and Organizational Tools for Large-Scale Scrum/Craig Larman, Bas Vodde/ 22-12-2008
27 SOA in Practice: The Art of Distributed System Design/Nicolai M. Josuttis/ 24-8-2007
28 Agile Testing: A Practical Guide for Testers and Agile Teams/Lisa Crispin, Janet Gregory/ 5-1-2009
29 The Business Analyst’s Handbook/Howard Podeswa/ 4-11-2008
30 Scrum and XP from the Trenches/Henrik Kniberg/ 4-10-2007
31 xUnit Test Patterns: Refactoring Test Code/Gerard Meszaros/ 31-5-2007
32 Applied SOA: Service-Oriented Architecture and Design Strategies/Michael Rosen, Boris Lublinsky, Kevin T. Smith, Marc J. Balcer/ 13-6-2008
33 97 Things Every Software Architect Should Know/Richard Monson-Haefel/ 13-2-2009 34 Perfect Software: And Other Illusions about Testing/Gerald M. Weinberg/ 29-8-2008
35 Expert Product Management: Advanced Techniques, Tips and Strategies for Product Management & Product Marketing/Brian Lawley/ 10-10-2007
36 The Enterprise and Scrum/Ken Schwaber/ 13-6-2007
37 Algorithms in a Nutshell/George Heineman, Gary Pollice, Stanley Selkow/ 1-11-2008
38 The Software Project Manager’s Bridge to Agility/Michele Sliger, Stacia Broderick/ 29-5-2008 39 Designing Web Interfaces: Principles and Patterns for Rich Interactions/Bill Scott, Theresa Neil/ 15-1-2008
40 If I Only Changed the Software, Why is the Phone on Fire?/Lisa K. Simone/ 23-3-2007
41 Puzzles for Programmers and Pros/Dennis Shasha/ 7-5-2007
42 Managing the Test People/Judy McKay/ 27-4-2007
43 Practical Project Initiation: A Handbook with Tools/Karl E. Wiegers/ 8-8-2007
44 Simple Architectures for Complex Enterprises/Roger Sessions/ 19-5-2008
45 How We Test Software at Microsoft/Alan Page, Ken Johnston, Bj Rollison/ 16-8-2008
46 The One Page Project Manager for IT Projects/Clark A. Campbell/ 4-8-2008
47 The Art of Lean Software Development: A Practical and Incremental Approach/Curt Hibbs, Steve Jewett, Mike Sullivan/ 15-12-2008
48 Code Leader: Using People, Tools, and Processes to Build Successful Software/Patrick Cauldwell/ 5-5-2008
49 Scrumban – Essays on Kanban Systems for Lean Software Development/Corey Ladas/ 12-1-2009
50 Software Requirement Patterns/Stephen Withall/ 13-6-2007



 

Written by everydayminder

April 9, 2009 at 00:26

Posted in Life/Memo

Tagged with , ,

현재 클래스 이름, 메소드 이름, 라인 넘버 얻기

leave a comment »

현재 실행하는 클래스의 이름과 메소드 이름, 라인 넘버를 얻어보자.

클래스의 인스턴스에서 호출한다는 가정하에,

def trace(obj, toList = False):
    import sys
    className = obj.__class__.__name__
    methodName = callersname()
    lineNumber = sys.exc_info()[2].tb_lineno
   
    if toList:
        return className, methodName, lineNumber
    else:
        return “%s.%s[%d]” % (className, methodName, lineNumber)

단, callersname()은

def callersname():
   return sys._getframe(2).f_code.co_name

그러나, 호출하는 클래스가 특정 클래스를 상속한 경우,
부모에 정의된 함수를 자식 클래스에서 그대로 사용하면서 trace()를 호출하였다면,
부모에 정의된 메소드를 실행하고 있더라도, 자식 클래스의 이름을
현재 클래스의 이름으로 리턴한다.

즉, A에 a()가 정의되어 있고, b = B(A)이나, b.a()를 실행도중 trace()를 호출하면,
현재 클래스의 이름이 A로 출력되는 대신 B로 출력된다.

Written by everydayminder

April 7, 2009 at 08:55

Posted in python

Tagged with , , ,

현재 함수의 이름 얻기

leave a comment »

# 현재 함수의 이름 얻기
def whoami():
    import sys
    return sys._getframe(1).f_code.co_name

# 현재 함수의 caller 이름 얻기
def callersname():
    import sys
    return sys._getframe(2).f_code.co_name


출처 : Python Recipe 66062: Determining Current Function Name

Written by everydayminder

April 7, 2009 at 06:39

Posted in python

Tagged with , , , , ,

How to catch ‘ExpatError exception’ (handling)

leave a comment »

ElementTree와 같은 패키지를 사용하여 XML를 파싱하는 경우,
XML 엘리먼트의 짝이 안맞는 등, 유효하지 않은 XML 구성이 탐지되면
ExpatError가 뜨는데,

try:
  # XML 연산
catch ExpatError, e:
  # do something

하면,
NameError: global name ‘ExpatError’ is not defined라는 에러가 뜬다.

이를 해결하려면,
ExpatError를 catch하는 py 파일의 앞에, scope을 맞춰서

from xml.parsers.expat  import ExpatError

라고 넣어주자. 그러면, 문제 해결!!


While you are using XML packages such as ElementTree, you might want to handle
ExpatError which might be caused by invalid-format or missing tags and so on.

However, you will see another error message saying “NameError: global name ‘ExpatError’
is not defined”.  What you only have to solve this problem is just add a line on the top of
your code.

That is,

from xml.parsers.expat import ExpatError

It’ll work, then.

Written by everydayminder

April 7, 2009 at 00:56

Posted in python

Tagged with , ,