@@ -343,21 +343,56 @@ void Python::Setup(const vector<string>& args) {
343343
344344bool Python::ExecutePythonFile (const string& file_path) {
345345#if DEVICE_STORAGE == 1
346- // Create pikascript-api directory for compiled output
347346 size_t last_slash = file_path.find_last_of (' /' );
348- if (last_slash != string::npos) {
349- string script_dir = file_path.substr (0 , last_slash);
350- string api_dir = script_dir + " /pikascript-api" ;
351-
352- // Check if directory exists, create if not
353- if (!MatrixOS::FileSystem::Exists (api_dir)) {
354- if (!MatrixOS::FileSystem::MakeDir (api_dir)) {
355- return false ;
356- }
347+ if (last_slash == string::npos) {
348+ MLOGD (" Python" , " No directory separator found in path: %s" , file_path.c_str ());
349+ return false ;
350+ }
351+
352+ // If the linked file path is already a py.a file.
353+ if (file_path.size () >= 5 && file_path.substr (file_path.size () - 5 ) == " .py.a" ) {
354+ // Link the library file and run "main" module
355+ MLOGD (" Python" , " Direct .py.a file execution: %s" , file_path.c_str ());
356+ obj_linkLibraryFile (pikaMain, (char *)file_path.c_str ());
357+ obj_runModule (pikaMain, (char *)" main" );
358+ return true ;
359+ }
360+
361+ // .py script
362+ string script_dir = file_path.substr (0 , last_slash + 1 ); // Include trailing slash
363+ string api_dir = script_dir + " pikascript-api" ;
364+
365+ // Check if directory exists, create if not
366+ if (!MatrixOS::FileSystem::Exists (api_dir)) {
367+ if (!MatrixOS::FileSystem::MakeDir (api_dir)) {
368+ MLOGD (" Python" , " Failed to create pikascript-api directory: %s" , api_dir.c_str ());
369+ return false ;
357370 }
358371 }
359372
360- pikaVM_runFile (pikaMain, (char *)file_path.c_str ());
373+ // Check if compiled byte code
374+ string lib_file = api_dir + " /pikaModules_cache.py.a" ;
375+ if (MatrixOS::FileSystem::Exists (lib_file)) {
376+ // Extract just the filename without extension
377+ string filename = file_path.substr (last_slash + 1 );
378+ size_t dot_pos = filename.find_last_of (' .' );
379+ if (dot_pos == string::npos) {
380+ MLOGD (" Python" , " No file extension found in filename: %s" , filename.c_str ());
381+ return false ;
382+ }
383+
384+ string filename_no_ext = filename.substr (0 , dot_pos);
385+
386+ // Link the library and run the module
387+ MLOGD (" Python" , " Found compiled library: %s" , lib_file.c_str ());
388+ MLOGD (" Python" , " Running module: %s" , filename_no_ext.c_str ());
389+ obj_linkLibraryFile (pikaMain, (char *)lib_file.c_str ());
390+ obj_runModule (pikaMain, (char *)filename_no_ext.c_str ());
391+ } else {
392+ // Run the file normally if no compiled library exists
393+ MLOGD (" Python" , " No compiled library found, running script directly: %s" , file_path.c_str ());
394+ pikaVM_runFile (pikaMain, (char *)file_path.c_str ());
395+ }
361396
362397 return true ;
363398#else
0 commit comments