【问题标题】:Python subprocess calling bcp on .csv: 'unexpected eof'Python 子进程在 .csv 上调用 bcp:'unexpected eof'
【发布时间】:2012-05-31 04:24:00
【问题描述】:

我在尝试 bcp 使用 Python 的 csv.writer 生成的 .csv 文件时遇到了 EOF 问题。我已经做了很多谷歌搜索,但没有运气,所以我求助于你们这些乐于助人的人

这是错误消息(在 subprocess.call() 行上触发):

Starting copy...
Unexpected EOF encountered in BCP data-file.
bcp copy in failed

代码如下:

sel_str = 'select blahblahblah...'
result = engine.execute(sel_str)  #engine is a SQLAlchemy engine instance

# write to disk temporarily to be able to bcp the results to the db temp table
with open('tempscratch.csv','wb') as temp_bcp_file:
    csvw = csv.writer(temp_bcp_file)
    for r in result:
        csvw.writerow(r)
        temp_bcp_file.flush()

# upload the temp scratch file
bcp_string = 'bcp tempdb..collection in @INFILE -c -U username -P password -S DSN'
bcp_string = string.replace(bcp_string,'@INFILE','tempscratch.csv')
result_code = subprocess.call(bcp_string, shell=True)

我在文本编辑器中查看了 tempscratch.csv 文件,没有看到任何奇怪的 EOF 或其他控制字符。此外,我查看了其他 .csv 文件进行比较,似乎没有 bcp 正在寻找的标准化 EOF。

另外,是的,这是 hacky,拉下结果集,将其写入磁盘,然后使用 bcp 将其重新上传到数据库。我必须这样做,因为 SQLAlchemy 在同一个 execute() 命令中不支持多行语句(又名 DDL 和 DML)。此外,此连接是与 Sybase db 的,它不支持 SQLAlchemy 的精彩 ORM :((这就是我首先使用 execute() 的原因)

标签: python csv sqlalchemy eof bcp


【解决方案1】:

据我所知,bcp 默认字段分隔符是制表符“\t”,而 Python 的 csv 编写器默认为逗号。试试这个...

# write to disk temporarily to be able to bcp the results to the db temp table
with open('tempscratch.csv','wb') as temp_bcp_file:
    csvw = csv.writer(temp_bcp_file, delimiter = '\t')
    for r in result:
        csvw.writerow(r)
    temp_bcp_file.flush()

【讨论】:

  • .flush() 在这里是不必要的。
猜你喜欢
  • 2013-09-26
  • 2014-05-20
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 2014-12-07
  • 2018-05-30
  • 1970-01-01
  • 2017-10-08
相关资源
最近更新 更多