Selecting GPU with Python script
Right now, I am using Blender 2.90. Here is my Python code to detect and use GPU in Blender.
import bpy
bpy.data.scenes[0].render.engine = &quot;CYCLES&quot;

# Set the device_type
bpy.context.preferences.addons[
    &quot;cycles&quot;
].preferences.compute_device_type = &quot;CUDA&quot; # or &quot;OPENCL&quot;

# Set the device and feature set
bpy.context.scene.cycles.device = &quot;GPU&quot;

# get_devices() to let Blender detects GPU device
bpy.context.preferences.addons[&quot;cycles&quot;].preferences.get_devices()
print(bpy.context.preferences.addons[&quot;cycles&quot;].preferences.compute_device_type)
for d in bpy.context.preferences.addons[&quot;cycles&quot;].preferences.devices:
    d[&quot;use&quot;] = 1 # Using all devices, include GPU and CPU
    print(d[&quot;name&quot;], d[&quot;use&quot;])
```