我正在尝试解析并异步JSON,但得到:
RuntimeWarning:从未等待协程'main'
import os
import pandas as pd
from datetime import datetime, timedelta
from google.cloud import bigquery
script_path = "C:\\Keys\\key.json"
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = script_path
client = bigquery.Client(project='project_id')
query_job = client.query("SELECT field1, field2, field3 FROM dataset.table ")
df = query_job.to_dataframe()
def to_xml(df, filename=None, mode='w'):
def row_to_xml(row):
xml = ['<item>']
for i, col_name in enumerate(row.index):
xml.append(' <field name="{0}">{1}</field>'.format(col_name, row.iloc[i]))
xml.append('</item>')
return '\n'.join(xml)
res = '\n'.join(df.apply(row_to_xml, axis=1))
if filename is None:
return res
with open(filename, mode, encoding="utf-8") as f:
f.write(res)
pd.DataFrame.to_xml = to_xml
df.to_xml('test.xml')
如何正确使用异步?
答案 0 :(得分:4)
如错误消息中所述,您必须等待主要功能,因为它是异步的。从the Python3.7 documentation section about coroutines 借来的
请注意,仅调用协程将不会安排其执行
鉴于您要运行顶级入口点,在Python 3.7+中应该使用
if __name__ == "__main__":
asyncio.run(main())
对于早期版本,您必须自己处理事件循环:
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())