pyVISA函数内调用.read()报错:会话/对象引用无效
Hey there! Let's break down why you're hitting that "The given session or object reference is invalid" error when moving your pyVISA read/write logic into a function—especially since it works fine in a while loop. Here are the most likely fixes:
1. Fix Variable Scope Issues
The most common culprit here is that your function can't access the my_instrument object correctly. In your while loop, you're probably using a global my_instrument variable, but inside the function, Python treats it as a local variable unless you explicitly tell it otherwise.
Try adding a global declaration at the start of your function to ensure it uses the global instrument instance:
def whatever(): global my_instrument # Tell Python to use the global instrument object my_instrument.write('MEASure:CURRent:DC?') value = my_instrument.read() voltage.append(value.strip('\n')) print(voltage)
Or, even better, pass the instrument object as a parameter to the function—this avoids scope confusion entirely and is cleaner practice (this is probably why your more complex tkinter/matplotlib code worked!):
def whatever(instrument): instrument.write('MEASure:CURRent:DC?') value = instrument.read() voltage.append(value.strip('\n')) print(voltage) # Call the function with your instrument instance whatever(my_instrument)
2. Check if the Instrument Session is Still Open
It's possible that somewhere in your code (before calling the function), you accidentally closed the instrument session with my_instrument.close(). Even a single misplaced close call can invalidate the session.
To debug this, print the session ID right before calling your function:
print(f"Current instrument session ID: {my_instrument.session}") whatever()
If the session ID is 0 or throws an error, you'll need to re-open the instrument connection before calling the function.
3. Rule Out Thread Safety Issues
If your simple program is using threads (even implicitly), keep in mind that pyVISA sessions aren't thread-safe. If your function is running in a different thread than where my_instrument was initialized, you might get this invalid session error.
Your complex matplotlib/tkinter code might have handled thread synchronization (e.g., using matplotlib's main thread for UI updates), but your simple program might not. If threading is involved, ensure all instrument interactions happen in the same thread that created the session.
内容的提问来源于stack exchange,提问作者user9185270

