简体   繁体   English

使用pycurl获得“ csv转储”

[英]using pycurl to get a “csv dump”

I'm trying to automate a tedious task to update the statuses of our change requests/cr's/bugs. 我正在尝试自动化一个繁琐的任务来更新更改请求/ cr / bug的状态。 Since the DataBase schema is extremely complex, I've resorted to issued a curl command to the web server to download a dump of the CRs along with their associated statuses. 由于数据库架构非常复杂,因此我不得不向Web服务器发出curl命令,以下载CR的转储及其相关状态。 I was doing with with an os.system() call but I've decided to make it more pythonic and use pycurl. 我正在使用os.system()调用进行处理,但是我决定使其更具pythonic并使用pycurl。 The problem, i think, is that when I write the downloaded csv to disk, the file is not completed yet when I go to access it (right after the c.perform() ). 我认为问题在于,当我将下载的csv写入磁盘时,当我去访问它时(在c.perform() ),文件尚未完成。 I'm lead to believe this because the error shows an list index out of range . 我之所以相信这一点,是因为错误显示list index out of range But when I open the file myself it looks like all the data is there. 但是,当我自己打开文件时,似乎所有数据都在那里。 Here's the code snippet (inside the find_bugs method I issue a split on each line and index into the relevant column of each row - that's where the list index comes in): 这是代码片段(在find_bugs方法中,我在每一行上进行拆分,并在每一行的相关列中建立索引-这就是列表索引所在的位置):

f = open(cr_file, 'w+')

c = pycurl.Curl()
c.setopt(c.URL, csv_url)
c.setopt(c.WRITEFUNCTION, f.write)
c.setopt(c.HTTPHEADER, headers)
c.perform()


with open(cr_file, 'r') as f:
  ids = find_bugs(f.readlines())

Question: How do I write to disk using pycurl when I need to immediately access the file once complete? 问题:完成后需要立即访问文件时,如何使用pycurl写入磁盘?

Until the first file object is flushed/closed, the file content may not be in the file. 在刷新/关闭第一个文件对象之前,文件内容可能不在文件中。

>>> f = open('text.csv', 'w+')
>>> f.write('asdf')
>>>
>>> f2 = open('text.csv', 'r')
>>> f2.read()
''
>>> f2.close()

After close : close

>>> f.close()
>>> f2 = open('text.csv', 'r')
>>> f2.read()
'asdf'

Because you open the file with w+ mode, you can use that file object to read the content: 因为您是使用w+模式打开文件的,所以可以使用该文件对象读取内容:

with open(cr_file, 'w+') as f:
    c = pycurl.Curl()
    c.setopt(c.URL, csv_url)
    c.setopt(c.WRITEFUNCTION, f.write)
    c.setopt(c.HTTPHEADER, headers)
    c.perform()

    f.seek(0)
    ids = find_bugs(f.readlines())

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

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