Beispiel #1
0
static foreign_t python_run_file(term_t file) {
  char *s;
  size_t len;
  char si[256];
  s = si;
  if (PL_get_nchars(file, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
#if PY_MAJOR_VERSION < 3
    PyObject *PyFileObject = PyFile_FromString(si, "r");
    PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1);
#else
    FILE *f = fopen(s, "r");
    if (f == NULL) {
      return false;
    }
    PyRun_SimpleFileEx(f, s, 1);
#endif
    {
      {
        return true;
      }
    }
  }
  {
    return false;
  }
}
bool PythonScripting::loadInitFile(const QString &path)
{
  QFileInfo pyFile(path+".py"), pycFile(path+".pyc");
  if (pycFile.isReadable() && (pycFile.lastModified() >= pyFile.lastModified()))
    return PyRun_SimpleFileEx(fopen(pycFile.filePath(), "rb"), pycFile.filePath(), true) == 0;
  else if (pyFile.isReadable()) {
    // try to compile pyFile to pycFile
    PyObject *compileModule = PyImport_ImportModule("py_compile");
    if (compileModule) {
      PyObject *compile = PyDict_GetItemString(PyModule_GetDict(compileModule),"compile");
      if (compile) {
	PyObject *tmp = PyObject_CallFunctionObjArgs(compile, PyString_FromString(pyFile.filePath()), PyString_FromString(pycFile.filePath()),NULL);
	if (tmp)
	  Py_DECREF(tmp);
	else
	  PyErr_Print();
      } else
	PyErr_Print();
      Py_DECREF(compileModule);
    } else
      PyErr_Print();
    if (pycFile.isReadable() && (pycFile.lastModified() >= pyFile.lastModified())) {
      // run the newly compiled pycFile
      return PyRun_SimpleFileEx(fopen(pycFile.filePath(), "rb"), pycFile.filePath(), true) == 0;
    } else {
      // fallback: just run pyFile
      return PyRun_SimpleFileEx(fopen(pyFile.filePath(), "r"), pyFile.filePath(), true) == 0;
    }
  }
  return false;
}
int main(int argc, char *argv[]) {
  // Set the python interpreter.
  setup_python(argc, argv);

  std::string filepath(argv[0]);

  // Get the path to the helper script.
  std::string helper_path;
  size_t path_end = filepath.find_last_of('\\');
  if (path_end != std::string::npos)
    helper_path = filepath.substr(0, path_end + 1);

  helper_path += "wbadminhelper.py";

  // Configures the execution of the script to take the same
  // parameters as this helper tool.
  Py_SetProgramName(argv[0]);

  PySys_SetArgv(argc, argv);

  // Executes the helper script.
  PyObject *pFileObject = PyFile_FromString(const_cast<char *>(helper_path.c_str()), "r");

  PyRun_SimpleFileEx(PyFile_AsFile(pFileObject), "wbadminhelper.py", 1);

  finalize_python();

  return 0;
}
Beispiel #4
0
int CPython::ExecFile(const std::vector<std::wstring> &argv, std::wstring &err, HANDLE hfile)
{
	int id = 0; FILE *pfile = nullptr; DWORD count = 0; 
	PyObject *poldout, *polderr, *pnewout, *pnewerr; 
	if (argv.size() <= 0) { 
		err = text("No python script file found"); return 1; 
	} 
	if (DuplicateHandle (
		GetCurrentProcess(), hfile, GetCurrentProcess(), &hfile, 
		0, false, DUPLICATE_SAME_ACCESS
	)) {
		id = open_osfhandle((intptr_t)hfile, _O_WRONLY); 
		pfile = fdopen(id,"w"); setvbuf(pfile,nullptr,_IONBF,1024);
		poldout = PySys_GetObject("stdout"); 
		polderr = PySys_GetObject("stderr");
		pnewout = PyFile_FromFile(pfile, "logger", "w", nullptr);
		pnewerr = PyFile_FromFile(pfile, "logger", "w", nullptr);
		PySys_SetObject("stdout", pnewout);
		PySys_SetObject("stderr", pnewerr);
	} else poldout = polderr = pnewout = pnewerr = nullptr;

	// Pack up the arguments ..
	std::vector<char*> args; int irslt = 0; 
	std::vector<std::wstring>::const_iterator itr, eitr; 
	std::wstring_convert<std::codecvt_utf8_utf16<wchar>> cvt; 
	itr = argv.cbegin(); eitr = argv.cend(); 
	for (size_t len = 0; itr != eitr; ++itr) { 
		// Allocate buffer each time, not good ..
		std::string str = cvt.to_bytes(*itr); 
		len = str.length(); char *arg = new char[len+1]; 
		strncpy_s(arg,len+1,str.data(),len); arg[len] = '\0'; 
		args.push_back(arg);
	}

	PySys_SetArgv(args.size(), args.data());	// pass args .
	PyObject *pobj = PyFile_FromString(args.at(0), "r");
	if (pobj == nullptr) {
		err = text("Internal error that PyFile_FromString fail"); 
		irslt = -1;
	} else {
		PyRun_SimpleFileEx(PyFile_AsFile(pobj), args.at(0), true);
		err = text("Execute python script file successfully .."); 
		irslt = 00;
	}

	// Free resource ...
	std::vector<char*>::iterator sitr, seitr;
	sitr = args.begin(); seitr = args.end();
	for (sitr; sitr != seitr; ++sitr) { if (*sitr) delete [] *sitr; }
	args.clear();

	if (pnewout != nullptr) PySys_SetObject("stdout", poldout);
	if (pnewerr != nullptr) PySys_SetObject("stderr", polderr);
	if (pfile != nullptr) fclose(pfile); return irslt;
}
	Module* PythonModule::CreateModule(std::string& path)
	{
		PyLockGIL lock;
		path = UTF8ToSystem(path);
		FILE* file = fopen(path.c_str(), "r");
		PyRun_SimpleFileEx(file, path.c_str(), 1);

		Poco::Path p(path);
		std::string basename = p.getBaseName();
		std::string name = basename.substr(0,basename.length()-python_suffix.length()+3);
		std::string moduledir = path.substr(0,path.length()-basename.length()-3);
		return new PythonModuleInstance(host, path, moduledir, name);
	}
Beispiel #6
0
int
PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
{
	if (filename == NULL)
		filename = "???";
	if (Py_FdIsInteractive(fp, filename)) {
		int err = PyRun_InteractiveLoop(fp, filename);
		if (closeit)
			fclose(fp);
		return err;
	}
	else
		return PyRun_SimpleFileEx(fp, filename, closeit);
}
Beispiel #7
0
int setup_virtualenv(){
	// Setup the given virtualenv for python, if given
	if (PY_VIRTUAL_ENV!=NULL){
		//char* cmd = "import os\nenv_path=u'";
		//cmd = combine(cmd, PY_VIRTUAL_ENV);
		//cmd = combine(cmd, "'\nif os.path.exists(env_path):\n"
		//			"    execfile(u'%s/activate_this.py'%(env_path),"
		//			"               dict(__file__=u'%s/activate_this.py'%(env_path)))");
		//PyRun_SimpleString(cmd);
		//PyRun_SimpleFile
		char* activateFile = combine(PY_VIRTUAL_ENV,"\\activate_this.py");
		PyObject* PyFileObject = PyFile_FromString(activateFile, "r");
		PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), activateFile, 1);
		}
	return 0;
	}
Beispiel #8
0
// Executed when script is called
void execscript(char* scriptname) {
    Py_SetProgramName("optimsoc_cli");

    Py_Initialize();

    printf("\nExecute script %s.\n\n", scriptname);

    Py_InitModule("optimsoc", pythonMethods);

    PyObject* file = PyFile_FromString(scriptname, "r");
    if (!file) {
        printf("Cannot find %s. Abort.\n",scriptname);
        return;
    }

    PyRun_SimpleString("from optimsoc import *");
    PyRun_SimpleFileEx(PyFile_AsFile(file), scriptname, 1);
}
Beispiel #9
0
int main(int argc, char **argv)
{
    Py_SetProgramName(argv[0]);

    /* uncomment this if you don't want to load site.py */
    /* Py_NoSiteFlag = 1; */

    Py_Initialize();

    char filename[] = "hello.py";
    PyObject* PyFileObject = PyFile_FromString(filename, "r");
    if (PyFileObject != NULL)
    {
        PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), filename, 1);
        Py_Finalize();
        return 1;
    }

    Py_Finalize();
    return 0;
}
Beispiel #10
0
int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s PYTHON_SCRIPT\n", argv[0]);
        return -1;
    }
    FILE *pyScript = fopen(argv[1],"r");
    if (pyScript == NULL) {
        fprintf(stderr, "ERROR: unable to open file '%s'\n", argv[1]);
        return -2;
    }

    initBSP(&argc, &argv);
    int err = PyRun_SimpleFileEx(pyScript,argv[1],1);
    if (err) {
        fprintf(stderr, "ERROR: failed to run file '%s' as a python script\n",
                argv[1]);
        return -3;
    }
    finiBSP();
    return 0;
}
Beispiel #11
0
	String PyInterpreter::runFile(const String& filename)
		throw(Exception::FileNotFound)
	{
		if (!valid_) return "";

		FILE* file = fopen(filename.c_str(), "r");

		if(!file)
		{
			throw Exception::FileNotFound(__FILE__, __LINE__, filename);
		}

		PyErr_Clear();
		PyRun_SimpleFileEx(file, filename.c_str(), true);

		if (PyErr_Occurred())
		{
			std::cout << "Error occured while executing " << filename << "\nPrinting Traceback:" << std::endl;
			PyErr_Print();
		}

		return "";
	}
Beispiel #12
0
int
PyRun_SimpleFile(FILE *fp, char *filename)
{
	return PyRun_SimpleFileEx(fp, filename, 0);
}