【问题标题】:why doesnt python run the main function?为什么python不运行main函数?
【发布时间】:2014-12-18 14:03:09
【问题描述】:

我是 python 的新手。我在问为什么 python 在我的情况下不运行 main 函数。我在主要功能的开头放置了一个打印功能,但它从不打印。尽管我设法运行其余代码以在互联网上创建我的 html 上传表单,但我确实设法在其上上传文件。你能帮忙吗?

这部分代码总是运行,不要问我怎么运行的:(

import web
import csv

urls = ('/upload', 'Upload')

class Upload:
    def GET(self):
        web.header("Content-Type","text/html; charset=utf-8")
        return """<html><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file"  name="myfile" />

<br/>
<input type="submit" />
</form>
</body></html>"""

    def POST(self):
        x = web.input(myfile={})

        outfile_errors = open('C:\Python27\csv_results\errors.csv', 'a')
        outfile_errors.write("in the post " + "\n " + str(x) + "\n " )

        filedir = "C:\Python27\csv_results\\"# change this to the directory you want to store the file in.
        if 'myfile' in x: # to check if the file-object is created

            filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.

            outfile_denumire_fisier = open('C:\Python27\csv_results\denumire_fisier.csv', 'a')
            outfile_denumire_fisier.write(filepath + ";" )
            outfile_denumire_fisier.close()

            filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
            fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete.


        raise web.seeother('/upload')
        #transform()
        outfile_errors.close()

这部分代码不起作用,至少不能与前面的代码一起使用。另外,它确实有效。

def transform():
        outfile_errors = open('C:\Python27\csv_results\errors.txt', 'a')
        outfile_errors.write("in the transform ")
        outfile_errors.close()
#bla bla

这是主要的,我在其中放置了一个打印到文件的功能,该功能永远不会起作用,尽管程序以某种方式运行第一个功能并生成我的 html 格式并允许我上传我想要的文件。很奇怪吧?

if __name__ == "__main__":
   outfile_errors = open('C:\Python27\csv_results\errors.csv', 'a')
   outfile_errors.write("in the main beginning" + "\n " )
   app = web.application(urls, globals()) 
   app.run()
   outfile_errors.write("in the main middle" + "\n " )
   transform()
   outfile_errors.write("in the main end " + "\n " )
   outfile_errors.close()

你能帮忙吗?

【问题讨论】:

  • 因为我认为app.run() 永远循环,因为它正在侦听网络请求。
  • 移除 name__='__main' 并显式调用语句。也许这会奏效。
  • @rgbimbochamp ...这甚至还没有接近正确的答案... Gohn67 有正确的答案
  • 好的。 app.run() 永远循环。知道如何调整我的程序吗?谢谢你的回报。

标签: python csv main ttl


【解决方案1】:

您没有告诉程序写入正确的变量。在 ma​​in 函数的后半部分将 outfile.write 更改为 Outfile_errors.write

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2015-09-19
    • 2022-10-02
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多