Error when linking after opening a file

Hi all,

In a script I’m trying to link an object after I opened a file:

bpy.ops.wm.open_mainfile(filepath = filename)
bpy.ops.wm.link_append(directory = filename2, files=[{'name':name}],link = False )

and I get this error on the second line:

Exception : <class ‘RuntimeError’>
Value : Operator bpy.ops.wm.link_append.poll() failed, context is incorrect

When I write those 2 lines in the python console it does what it should (opening my file and linking my object).

I get the same error when I open the default file like that:

bpy.ops.wm.read_homefile()
bpy.ops.wm.link_append(directory = filename2, files=[{'name':name}],link = False )

When I don’t open any file and I just link my object, my script works.

this works:

bpy.ops.wm.link_append(directory = filename2, files=[{'name':name}],link = False )

Any ideas would be helpful.