Python, AttributeError: module 'google.cloud.bigquery' has no attribute 'Client' after cx_Freeze build

Viewed 6375

I'm trying to use cx_Freeze to create an executable of a script which loads an .sql query from the same folder, executes it on a BigQuery DB and returns a .csv of the retrieved data.

  This is what the 'conda list' command gives me:
  google-api-core           1.1.0                      py_0    conda-forge
  google-auth               1.6.2                      py_0    conda-forge
  google-cloud-bigquery     1.8.1                      py_0    conda-forge  
  google-cloud-core         0.28.1                     py_0    conda-forge
  google-resumable-media    0.3.1                      py_0    conda-forge
  googleapis-common-protos  1.5.5                      py_0    conda-forge

The script crashes in the first lines (KEY and PROJECT_ID are specified in the script but not pasted for security reasons)

from google.cloud import bigquery
client = bigquery.Client.from_service_account_json(KEY, project=PROJECT_ID)

My setup.py for cx_Freeze looks like this:

from cx_Freeze import setup, Executable

setup(name='output_script', executables = [Executable("my_script.py")], version="1.0.0",
options={
         "build exe":{"packages":["google.cloud.bigquery, google.cloud.bigquery.client"]}})

The build executes successfully, however when I run my_script.exe in the build folder I get the following error:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run
    module.run()
  File "C:\ProgramData\Anaconda3\lib\site-packages\cx_Freeze\initscripts\Console.py", line 26, in run
    exec(code, m.__dict__)
  File "my_script.py", line 15, in <module>
  File "my_script.py", line 7, in queryBigQ
AttributeError: module 'google.cloud.bigquery' has no attribute 'Client'

Tried reinstalling and updating all Google packages but no success. Any pointers would be appreciated.

2 Answers

Did you try to run your script successfully before freezing it?

It looks like your local development environment is missing the bigquery library. Make sure that you create a virtualenv and install bigquery library in it.

Test the connection to BigQuery with a simple script:

from google.cloud import bigquery

client = bigquery.Client()

QUERY = (
    'SELECT * FROM `[PROJECT_ID].[BQ_INSTANCE].[BQ_TABLE]`'
)
query_job = client.query(QUERY)
rows = query_job.result()

for row in rows:
    print(row)

Try with

from google.cloud.bigquery.client import Client
client = Client.from_service_account_json(KEY, project=PROJECT_ID)

or maybe

from google.cloud.bigquery import Client
client = Client.from_service_account_json(KEY, project=PROJECT_ID)

in your main script.

Try also to replace the options argument in your setup.py script by

options={"build exe": {"packages": ["google"]}}
Related