2013-08-15 1 views
1

내가 아주 간단한 될 것입니다 확신 어떤 것을 다시 확실 해요 ...스크립트로 인해 정의되지 않은 기능을 기본적으로

여러 다른 스크립트 erroring를 호출, 내 첫 번째 스크립트 호출을하기 위해 노력하고있어

다음
from datetime import date, timedelta 
from sched import scheduler 
from time import time, sleep, strftime 
import random 

s = scheduler(time, sleep) 
random.seed() 

def periodically(runtime, intsmall, intlarge, function): 
    ## Get current time 
    currenttime = strftime('%H:%M:%S') 

    ## If currenttime is anywhere between 23:40 and 23:50 then... 
    if currenttime > '23:40:00' and currenttime < '23:50:00': 
     ## Call clear 
     clear() 
     ## Update time 
     currenttime = strftime('%H:%M:%S') 

    ## Idle time 
    while currenttime > '23:40:00' and currenttime < '23:59:59' or currenttime >= '00:00:00' and currenttime < '01:30:00': 
     ## Update time 
     currenttime = strftime('%H:%M:%S') 

    runtime += random.randrange(intsmall, intlarge) 
    s.enter(runtime, 1, function,()) 
    s.run() 

def callscripts(): 
    print "Calling Functions" 

    errors = open('ERROR(S).txt', 'a') 
    try: 
     execfile("data/secondary.py") 
    except Exception as e: 
     errors.write(str(e)) 
     errors.write(""" 
""")   
    errors.close() 


while True: 
    periodically(2, -1, +1, callscripts) 

은 다음과 같습니다/

첫 번째 스크립트/주요 스크립트 ... 다른 스크립트의 무리를 실행하지만 문제는 각 개별 스크립트가 자신의 기능을 처음 secript에서 호출 할 수 없습니다 포함시킬 것입니다 secondary.py

import win32con 
from win32api import * 
from win32gui import * 

class WindowsBalloonTip: 
    def __init__(self, title, msg): 
     message_map = { win32con.WM_DESTROY: self.OnDestroy,} 

     # Register the window class. 
     wc = WNDCLASS() 
     hinst = wc.hInstance = GetModuleHandle(None) 
     wc.lpszClassName = 'PythonTaskbar' 
     wc.lpfnWndProc = message_map # could also specify a wndproc. 
     classAtom = RegisterClass(wc) 

     # Create the window. 
     style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU 
     self.hwnd = CreateWindow(classAtom, "Taskbar", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) 
     UpdateWindow(self.hwnd) 

     # Icons managment 
     iconPathName = "icon1.ico" ## LOCATION TO THE ICON FILE 
     icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE 
     try: 
      hicon = LoadImage(hinst, iconPathName, win32con.IMAGE_ICON, 0, 0, icon_flags) 
     except: 
      hicon = LoadIcon(0, win32con.IDI_APPLICATION) 
     flags = NIF_ICON | NIF_MESSAGE | NIF_TIP 
     nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, 'Tooltip') 

     # Notify 
     Shell_NotifyIcon(NIM_ADD, nid) 
     Shell_NotifyIcon(NIM_MODIFY, (self.hwnd, 0, NIF_INFO, win32con.WM_USER+20, hicon, 'Balloon Tooltip', msg, 200, title)) 
     # self.show_balloon(title, msg) 
     sleep(5) 

     # Destroy 
     DestroyWindow(self.hwnd) 
     classAtom = UnregisterClass(classAtom, hinst) 
    def OnDestroy(self, hwnd, msg, wparam, lparam): 
     nid = (self.hwnd, 0) 
     Shell_NotifyIcon(NIM_DELETE, nid) 
     PostQuitMessage(0) # Terminate the app. 

# Function 
def balloon_tip(title, msg): 
    w=WindowsBalloonTip(title, msg) 


balloon_tip("test test", "Running") 

def hi(): 
    print "hi" 

hi() 

오류 :

global name 'WindowsBalloonTip' is not defined 

전체 오류 :

Traceback (most recent call last): 
    File "C:\Main.py", line 48, in <module> 
    periodically(2, -1, +1, callscripts) 
    File "C:\Main.py", line 27, in periodically 
    s.run() 
    File "C:\Python27\lib\sched.py", line 117, in run 
    action(*argument) 
    File "Main.py", line 34, in callscripts 
    execfile("data/secondary.py") 
    File "data/secondary.py", line 93, in <module> 
    balloon_tip("test test", "Running") 
    File "data/secondary.py", line 78, in balloon_tip 
    w=WindowsBalloonTip(title, msg) 
NameError: global name 'WindowsBalloonTip' is not defined 

가 어떻게이 문제를 해결 가겠어요? 사전에

감사 Hyflex

+0

게시하시기 바랍니다 전체 ** ** 오류 추적은 - 그것의 정보는 도움을주기위한 것입니다 코드를 디버깅하여 게시해야합니다. – Brionius

+0

그 파일에서 전체 오류 추적입니다, 만약 당신이 그것을 실행하고 잘 작동하는 main.py를 통해 그것을 실행하는 경우 작동하지 않는 의도로 자신을 실행하는 경우 secondary.py. 위의 두 스크립트는 오류를 완벽하게 재현 할 수 있습니다. – Ryflex

+0

추적을 사용하지 않고 문제를 실제로 확인할 수는 없습니다. 하지만 모듈을 작성하고 import 문을 사용하는 방법을 살펴볼 수 있다고 생각합니다. 함수를 파일에 정의하고 모듈 수준에서 그 함수를 호출하는 대신'import secondary'와 같은 첫 번째 스크립트에서 모듈을 가져와'secondary.balloon_tip()'과 같은 함수를 호출해야합니다. 이것은 모듈 식 코드를 작성하는 올바른 방법입니다. – Iguananaut

답변

3

첫째, 이전 버전과의 호환성을 위해.

Ethan의 대답은 정확하지만이 질문을하는 경우 아마도 분명하지 않을 수 있습니다. 전체 설명은 here입니다.

ballon_tip()을 실행하면 로컬 이름 공간 인 balloon_tip()의 네임 스페이스를 검색하여 WindowsBalloonTip이라는 항목을 찾습니다. 찾을 수 없으면 글로벌 네임 스페이스를 검색합니다. globals 매개 변수에 execfile()에 대한 값을 제공하지 않았으므로 기본값은 WindowsBaloonTip 안에 아무 것도 없으며 오류가있는 callscripts()의 네임 스페이스이며 오류가 발생합니다.

이 문제를 해결하려면 execfileglobals()을 인수로 전달할 수 있지만, 원치 않는 주요 스크립트의 전역 네임 스페이스가 오염 될 수 있습니다. 또한 secondary.py 내부의 모든 것을 전역으로 선언 할 수도 있지만, 전체적으로 secondary.py를 테스트하는 것이므로이 작업을 원하지 않을 것입니다.

문제는 execfile입니다. execfile은 일을하는 추악한 해킹 방법입니다. import이 좋습니다.

def test_harness(): 
    balloon_tip("test test", "Running") 
    hi() 

후, 메인 스크립트 내부 import secondary, traceback, 변경 callscripts()이 같은 : 코멘트에 대한 응답으로

def callscripts(): 
     print "Calling Functions" 
     errors = open("ERRORS(S).txt", "a") 

     try: 
      secondary.test_harness() 
     except: 
      errors.write(traceback.format_exc() + '\n') 

EDIT 하나 개의 솔루션이 내부 secondary.py 뭔가를 작성하는 것입니다 : 다음 스크립트 import traceback의 상단에 :

def callscripts(): 
     print "Calling Functions" 
     errors = open("ERRORS(S).txt", "a") 

     try: 
      execfile("data/secondary.py", {}) 
     except: 
      errors.write(traceback.format_exc() + '\n') 
+0

매우 상세한 답변을 주셔서 감사합니다.이 작업을 수행하는 유일한 문제는 일련의 함수를 실행하는 함수를 효과적으로 생성해야한다는 것입니다 ... 이상적으로 저는 수동으로 secondary.py를 실행할 수 있기를 원합니다. 즉각적인 결과를 얻고, main.py를 통해 실행하면 수입 내에서 특정 기능을 특별히 호출하지 않고도 동일한 결과를 얻을 수 있습니다. – Ryflex

+1

'execfile (script_path, {})'을 시도하십시오. 내 로컬 컴퓨터에서 작동합니다. –

+0

전체 traceback이 더 좋으므로 앞의 답변과 같은 종류의 traceback 작성으로 방금 언급 한 execfile 메소드를 어떻게 사용할 수 있습니까? – Ryflex

1

The problem is execfile.

는 기본적으로, execfile는 파일과 멋진 exec이다. 따라서 execfile 'secondary.py'을 호출하면 파이썬은 execfile이 호출 된 곳의 컨텍스트에서 secondary.py의 모든 행을 실행합니다.이 경우 callscripts 함수 안에 있습니다.

아마도 원하는 것은 subprocess입니다. 전자는 파이썬 3에서 사라졌습니다 이전 스타일 클래스이며, 파이썬 2.x에서 만의 최신 버전에 있기 때문에

class WindowsBalloonTip: 

class WindowsBalloonTip(object): 

해야 모든

+0

이러한 상황에서 하위 프로세스를 사용하는 방법에 대한 예제를 제공 할 수 있습니까? 위에 나열된 코드로 작업 할 수 있습니까? – Ryflex

관련 문제