使用Chaquopy从Kotlin向Python传递字符串值失败的问题求助
Hey there! Let's figure out why your movie string isn't making it from Kotlin to your Python script, and why your output file is coming up empty. I've tackled similar Chaquopy quirks before, so let's walk through fixes step by step:
1. First, Verify the Basics: Is Your Parameter Even Valid?
Before diving into Chaquopy specifics, make sure the movie variable you're passing isn't null or empty. Add a quick check in your Kotlin code to confirm:
if (!Python.isStarted()) { Python.start(AndroidPlatform(requireContext())) } val py = Python.getInstance() val pyobj = py.getModule("testScript") // Check if movie is valid and module loaded if (movie.isNullOrEmpty()) { Log.e("Chaquopy", "Movie string is null or empty!") } else if (pyobj == null) { Log.e("Chaquopy", "Failed to load testScript module - check file location!") } else { val result = pyobj.callAttr("main", movie) as String Log.d("ChaquopyResult", "Python returned: $result") // Log the return value to debug }
This will rule out simple issues like a missing module or empty input.
2. Fix the File Path in Your Python Script
Your original path logic might be pointing to a directory you don't have write access to. getFilesDir() returns your app's private, writable directory—no need to jump to its parent. Update your Python code to use this directly:
import os import sys def main(movie): try: # Get the correct app files directory app_files_dir = str(Python.getPlatform().getApplication().getFilesDir()) filename = os.path.join(app_files_dir, "file.txt") # Skip stdout redirection (it's prone to buffering issues) and write directly with open(filename, 'w', encoding='utf8', errors="ignore") as f: f.write(f"Received movie: {movie}\n") # Read and return the content to confirm with open(filename, 'r', encoding='utf8') as f: output = f.read() return output # Catch and return any errors to debug in Kotlin except Exception as e: return f"Error in Python: {str(e)}"
Redirecting sys.stdout can cause unexpected issues (like buffered content not writing before closing), so writing directly to the file is more reliable.
3. Double-Check Your Chaquopy Setup
Make sure your project is configured correctly for Chaquopy:
- Ensure
testScript.pyis placed insrc/main/python/(this is the default directory Chaquopy looks for Python scripts). - Verify your app-level
build.gradlehas the correct Chaquopy configuration (use the latest version for bug fixes):
plugins { id 'com.android.application' id 'kotlin-android' id 'com.chaquo.python' } android { defaultConfig { ndk { abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64" } python { // Add any pip dependencies here if needed } } } dependencies { implementation 'com.chaquo.python:chaquopy:14.0.2' // Use the latest version available }
4. Test with a Hardcoded String First
To isolate the issue, try passing a hardcoded string instead of the movie variable in Kotlin:
pyobj.callAttr("main", "Test Movie Title")
If this works, the problem is with how movie is being passed from the previous Fragment (maybe it's not being set correctly there). If it still fails, the issue is in your Chaquopy setup or Python code.
Final Notes
By adding logging, fixing the file path, avoiding stdout redirection, and validating inputs, you should be able to pinpoint exactly where the breakdown is. The exception handling in Python will give you clear error messages if something's going wrong (like permission issues or missing imports).
内容的提问来源于stack exchange,提问作者Greg Aw Mun Hong

