简体   繁体   English

如何在python中全局导入?

[英]How do I do global import in python?

I was just getting started with reportlab, when I stumbled upon something. 当我偶然发现某些东西时,我才刚刚开始使用reportlab。 I started with some basic code: 我从一些基本代码开始:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

def generateDoc(docName, title, codefilesFolderPath, docTextFilePath):

    canvas = canvas.Canvas(docName, pagesize=letter) 
    canvas.setLineWidth(.3)
    canvas.setFont('Helvetica', 12)
    canvas.drawString(30,750,'OFFICIAL COMMUNIQUE')
    canvas.save()

generateDoc("temp.pdf","","","")

It was giving me following error: 它给了我以下错误:

UnboundLocalError: local variable 'canvas' referenced before assignment

I have come to know that global variables are not freely allowed in python as in case of other languages and this post asks to use global keyword. 我已经知道,像其他语言一样,不允许在python中自由允许使用全局变量,并且本帖子要求使用global关键字。 However I am unable to get how I am supposed to do that in above code. 但是我无法在上面的代码中得到应该怎么做。

I tried putting import at various places, but I am not able to get how do I do this. 我曾尝试在不同的地方放置import ,但无法获得如何执行此操作的信息。

Your local variable canvas hides the imported module canvas . 您的本地变量canvas隐藏了导入的模块canvas

You could import Canvas directly: 您可以直接导入Canvas

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas

def generateDoc(docName, title, codefilesFolderPath, docTextFilePath):

    canvas = Canvas(docName, pagesize=letter) 
    canvas.setLineWidth(.3)
    canvas.setFont('Helvetica', 12)
    canvas.drawString(30,750,'OFFICIAL COMMUNIQUE')
    canvas.save()

generateDoc("temp.pdf","","","")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM