| 404 | |
| 405 | |
| 406 | int NGS_LoadPy (ClientData clientData, |
| 407 | Tcl_Interp * interp, |
| 408 | int argc, const char *argv[]) |
| 409 | { |
| 410 | if(!netgen::netgen_executable_started) { |
| 411 | Ng_Tcl_SetResult (interp, (char*)"This feature is not available when running from Python", NG_TCL_STATIC); |
| 412 | return NG_TCL_ERROR; |
| 413 | } |
| 414 | |
| 415 | if (Ng_IsRunning()) |
| 416 | { |
| 417 | Ng_Tcl_SetResult (interp, (char*)"Thread already running", NG_TCL_STATIC); |
| 418 | return NG_TCL_ERROR; |
| 419 | } |
| 420 | |
| 421 | if (argc >= 2) |
| 422 | { |
| 423 | try |
| 424 | { |
| 425 | string filename = argv[1]; |
| 426 | cout << IM(3) << "(should) load python file '" << filename << "'" << endl; |
| 427 | |
| 428 | #ifdef NGS_PYTHON |
| 429 | { |
| 430 | std::thread([](string init_file_) |
| 431 | { |
| 432 | AcquireGIL gil_lock; |
| 433 | try{ |
| 434 | Ng_SetRunning (1); |
| 435 | pythread_id = std::this_thread::get_id(); |
| 436 | |
| 437 | // change working directory to the python file |
| 438 | stringstream s; |
| 439 | s << "import os" << endl |
| 440 | << "os.chdir(os.path.dirname(os.path.abspath('" << init_file_ << "')))" << endl |
| 441 | << "del os" << endl; |
| 442 | |
| 443 | // set sys.argv |
| 444 | s << "import sys" << endl; |
| 445 | s << "sys.argv = ["; |
| 446 | if(h_argc > 1) |
| 447 | for(auto i : Range(2, h_argc)) |
| 448 | { |
| 449 | if(i>0) s << ',' << endl; |
| 450 | s << '"' << h_argv[i] << '"'; |
| 451 | } |
| 452 | s << ']' << endl; |
| 453 | pyenv.exec(s.str()); |
| 454 | |
| 455 | pyenv.exec_file(init_file_.c_str()); |
| 456 | Ng_SetRunning (0); |
| 457 | } |
| 458 | catch (py::error_already_set const &) { |
| 459 | PyErr_Print(); |
| 460 | } |
| 461 | cout << IM(3) << "Finished executing " << init_file_ << endl; |
| 462 | |
| 463 | pythread_id = mainthread_id; |