全局变量和函数Python

时间:2013-08-06 13:50:15

标签: python

我正在尝试在一个函数中使用另一个函数中定义的变量。我知道我必须使用Global var,但我仍然没有得到我期望的输出。

def proxycall():
    global ip
    global port
    ip = "192.168.0.1"
    port = "8080"


def web1():
    class YWebPage():
        def something():
            var = 1
        def somethingelse():
            varr = 2
    class Browser():
        def someting():
            varrr = 3
        def sometingelse():
            varrrr = 4

    print (ip)
    print (port)

web1()

我的程序的这个最小版本提供了回溯 - NameError:未定义全局名称'ip'。


我现在看到了最小版本的问题,感谢您指出。但是我现在不认为这是我的问题,因为我在下面的完整版中调用了proxycall(),任何想法?

import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from PyQt4.QtWebKit import QWebSettings
from PyQt4.QtNetwork import QNetworkAccessManager
from PyQt4.QtNetwork import *
import re
import requests

UA_STRING = """Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36""" # String for User-Agent
#vidurl = "http://www.youtube.com/watch?v=hqDT6G5_1tQ" # 94 views
vidurl = "http://httpbin.org"


def proxycall():
            global ip
            global port
                # Proxy Stuff
            count = 0
            while (count < 5):

                 #Call mashape proxy API and setup
              try:
                 headers = {'X-Mashape-Authorization':'xxxxxxxxxxxxx'}
                 p = requests.get('https://webknox-proxies.p.mashape.com/proxies/new?maxResponseTime=5', headers=headers, timeout=5.000)
                 prox = p.text
                 ip = prox.split(":")[1]   #split response string
                 port = prox.split(":")[2]
                 ip = re.sub('["}]', '', ip)   #sanitize output
                 port = re.sub('["}]', '', port)
                 proxy = str(ip) + ':' + str(port) #reformat proxy for Requests
                 print ('Retrieved proxy ' + str(proxy))
                 proxies = {"http": proxy}
                 print ('Configured proxy')
              except:
                 print('Mashape API error, FAIL')

                 #Get real IP address
              try:
                 r = requests.get('http://httpbin.org/ip', timeout=5.000)
                 s = r.text
                 realip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', s )
                 print ('Real IP address is ' + str(realip))
              except:
                 print ("Connection Error (IP), FAIL")

                 #Test proxy
              try:
                 x = requests.get('http://bot.whatismyipaddress.com/', proxies=proxies, timeout=5.000)
                 y = x.text
                 proxyip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', y )
                 print ('Masked IP address is ' + str(proxyip))
                 if proxyip != realip:
                    print ('Proxy test OK')
                    count = 100
                 else:
                    print ('Proxy test FAIL, GET new proxy...')  
              except:
                 print ("Connection Error (Proxy), FAIL")

def web1(parent):

    class YWebPage(QtWebKit.QWebPage):
        def __init__(self):
            super(QtWebKit.QWebPage, self).__init__()

        def userAgentForUrl(self, url):
            return UA_STRING


    class Browser(QtGui.QMainWindow): # "Browser" window


        def __init__(self, parent):
            QtGui.QMainWindow.__init__(self, parent)
            self.resize(800,600) # Viewport size
            self.centralwidget = QtGui.QWidget(self)
            self.html = QtWebKit.QWebView()


        def browse(self):
            self.webView = QtWebKit.QWebView()
            self.yPage = YWebPage()
            self.webView.setPage(self.yPage)
            self.webView.load(QtCore.QUrl(vidurl)) # Video URL
            self.webView.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled,True) # Enables flash player
            self.webView.settings().setAttribute(QtWebKit.QWebSettings.AutoLoadImages, False) # No images for speed
            QWebSettings.clearMemoryCaches ()
            self.webView.show()
            proxycall()


    x = Browser(parent)
    QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, ip, port))
    x.browse()

5 个答案:

答案 0 :(得分:3)

您根本没有调用proxycall(),因此从未设置变量。

先调用它,然后调用web1()

proxycall()
web1()

名称不仅仅因为你在函数中将它们标记为global而才会存在; Python名称需要赋值(绑定)才能实现。

答案 1 :(得分:1)

您需要先调用proxycall()才能全局访问ip

proxycall()
web1()

答案 2 :(得分:0)

您需要致电proxycall()初始化ip

proxycall()
web1()

答案 3 :(得分:0)

在使用之前,您需要初始化/定义ipport。致电proxycall(),然后致电web1()

 def proxycall():
        global ip
        global port
        ip = "192.168.0.1"
        port = "8080"


    def web1():
        class YWebPage():
            def something():
                var = 1
            def somethingelse():
                varr = 2
        class Browser():
            def someting():
                varrr = 3
            def sometingelse():
                varrrr = 4

        print (ip)
        print (port)

    proxycall()
    web1()

ANS: 192.168.0.1 8080

答案 4 :(得分:0)

您更新的代码与原始代码存在同样的问题。您在此声明中使用ip:

QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, ip, port))

...但是在此之后的语句中调用proxycall之前,您不会致电x.browse()