Exemplo n.º 1
0
static PyObject *
svc_writefile(captureobject *self, PyObject *args)
{
	PyObject *file;
	int size;
	FILE* fp;

	if (!PyArg_Parse(args, "O", &file))
		return NULL;

	if (!PyFile_Check(file)) {
		PyErr_SetString(SvError, "not a file object");
		return NULL;
	}

	if (!(fp = PyFile_AsFile(file)))
		return NULL;

	size = self->ob_info.width * self->ob_info.height;

	if (fwrite(self->ob_capture, sizeof(long), size, fp) != size) {
		PyErr_SetString(SvError, "writing failed");
		return NULL;
	}

	Py_INCREF(Py_None);
	return Py_None;
}
Exemplo n.º 2
0
Arquivo: strcaps.c Projeto: mk-fg/fgc
static PyObject *
strcaps_get_file(PyObject *self, PyObject *args) { // (int) fd / (str) path / (file) file
	PyObject *file;
	if (!PyArg_ParseTuple(args, "O", &file)) return NULL;
	cap_t caps;
	if (PyFile_Check(file)) caps = cap_get_fd(PyObject_AsFileDescriptor(file));
	else if (PyInt_Check(file)) caps = cap_get_fd(PyInt_AsLong(file));
	else if (PyString_Check(file)) caps = cap_get_file(PyString_AsString(file));
	else if (PyUnicode_Check(file)) {
		PyObject *file_dec = PyUnicode_AsEncodedString(
			file, Py_FileSystemDefaultEncoding, "strict" );
		if (file_dec == NULL) return NULL;
		caps = cap_get_file(PyString_AsString(file_dec));
		Py_DECREF(file_dec); }
	else {
		PyErr_SetString( PyExc_TypeError,
			"Expecting file object, descriptor int or path string" );
		return NULL; }
	size_t strcaps_len; char *strcaps;
	if (caps == NULL) {
		if (errno == ENODATA) { strcaps = "\0"; strcaps_len = 0; }
		else {
			PyErr_SetFromErrno(PyExc_OSError);
			return NULL; } }
	else strcaps = cap_to_text(caps, &strcaps_len);
	cap_free(caps);
	return Py_BuildValue("s#", strcaps, strcaps_len); }; // (str) caps
Exemplo n.º 3
0
/* Call with the basis file */
static PyObject*
_librsync_new_patchmaker(PyObject* self, PyObject* args)
{
  _librsync_PatchMakerObject* pm;
  PyObject *python_file;
  FILE *cfile;

  if (!PyArg_ParseTuple(args, "O:new_patchmaker", &python_file))
	return NULL;
  if (!PyFile_Check(python_file)) {
	PyErr_SetString(PyExc_TypeError, "Need true file object");
	return NULL;
  }
  Py_INCREF(python_file);
  
  pm = PyObject_New(_librsync_PatchMakerObject, &_librsync_PatchMakerType);
  if (pm == NULL) return NULL;
  pm->x_attr = NULL;

  pm->basis_file = python_file;
  cfile = PyFile_AsFile(python_file);
  pm->patch_job = rs_patch_begin(rs_file_copy_cb, cfile);

  return (PyObject*)pm;
}
Exemplo n.º 4
0
Arquivo: strcaps.c Projeto: mk-fg/fgc
static PyObject *
strcaps_set_file(PyObject *self, PyObject *args) { // (str) caps, (int) fd / (str) path / (file) file
	char *strcaps; PyObject *file;
	if (!PyArg_ParseTuple(args, "etO",
		Py_FileSystemDefaultEncoding, &strcaps, &file)) return NULL;
	cap_t caps;
	if ((caps = cap_from_text(strcaps)) == NULL) {
		PyErr_SetString(PyExc_ValueError, "Invalid capability specification");
		PyMem_Free(strcaps);
		return NULL; }
	PyMem_Free(strcaps);
	int err;
	if (PyFile_Check(file)) err = cap_set_fd(PyObject_AsFileDescriptor(file), caps);
	else if (PyInt_Check(file)) err = cap_set_fd(PyInt_AsLong(file), caps);
	else if (PyString_Check(file)) err = cap_set_file(PyString_AsString(file), caps);
	else if (PyUnicode_Check(file)) {
		PyObject *file_dec = PyUnicode_AsEncodedString(
			file, Py_FileSystemDefaultEncoding, "strict" );
		if (file_dec == NULL) return NULL;
		err = cap_set_file(PyString_AsString(file_dec), caps);
		Py_DECREF(file_dec); }
	else {
		PyErr_SetString( PyExc_TypeError,
			"Expecting file object, descriptor int or path string" );
		cap_free(caps);
		return NULL; }
	cap_free(caps);
	if (err) {
		PyErr_SetFromErrno(PyExc_OSError);
		return NULL; }
	Py_RETURN_NONE; };
Exemplo n.º 5
0
static int Polygon_init(Polygon *self, PyObject *args, PyObject *kwds) {
    PyObject *O = NULL, *TMP = NULL;
    int hole;
    static char *kwlist[] = {"contour", "hole", NULL};
    if (! PyArg_ParseTupleAndKeywords(args, kwds, "|Oi", kwlist, &O, &hole))
        return -1; 
    if (O != NULL) {
        if ((PyTypeObject *)PyObject_Type(O) == &Polygon_Type) {
            if (poly_p_clone(((Polygon *)O)->gpc_p, self->gpc_p) != 0) {
                Polygon_dealloc(self);
                Polygon_Raise(ERR_MEM);
                return -1;
            }
        } else if (PyString_Check(O)) {
            TMP = Polygon_read(self, args);
        } else if (PySequence_Check(O)) {
            TMP = Polygon_addContour(self, args);
        } else if (PyFile_Check(O)) {
            TMP = Polygon_read(self, args);
        } else {
            Polygon_Raise(ERR_ARG);
            return -1;
        }
        if (TMP) {
            Py_DECREF(TMP);
        }
    }
    return 0;
}
Exemplo n.º 6
0
/*
  dummy.decode_command_n(stream, N) -> ((cmd_code, args), .... (cmd_code_N, args_N))
 */
static PyObject *
dummy_decode_command(PyObject *self, PyObject *args) {
  int N = 1;

  PyObject *po = PyTuple_GetItem(args, 0);
  if (!PyFile_Check(po)) {
    PyErr_SetString(DummyError, "First argument should be  a file object.");
    return NULL;
  }
  if (PyTuple_Size(args) == 2) {
    PyObject *pn = PyTuple_GetItem(args, 1);
    N = PyInt_AS_LONG(pn);
  }

  hu::FileInStream stream;
  FILE *handle = PyFile_AsFile(po);
  stream.open(handle);

  PyObject* res = PyTuple_New(N);
  
  for(int i = 0;  i < N ; ++i) {
    PyObject* cmd = decoder.decode_cmd_from_stream(stream);
    if (cmd == NULL) {
      return NULL;
    }
    PyTuple_SET_ITEM(res, i, cmd);
    if (PyInt_AS_LONG(PyTuple_GetItem(cmd, 0)) == CLOSE) {
      _PyTuple_Resize(&res, i + 1);
      return res;
    }
  }
  return res;
}
Exemplo n.º 7
0
static PyObject* cdb_py_print_records(PyObject *self, PyObject *args, PyObject *kwdict) {
  static char *kwlist[] = {
    "start", "end", "count", "cooked", "step", "file_obj", "date_format", NULL,
  };

  cdb_time_t start = 0;
  cdb_time_t end   = 0;
  int cooked       = 1;
  long step        = 0;
  int64_t count    = 0;
  cdb_t *cdb;
  PyObject *file_obj, *date_format;

  if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|LLLOzil:print_records", kwlist, &start, &end, &count, &file_obj, &date_format, &cooked, &step)) {
    return NULL;
  }

  cdb_request_t request = _parse_cdb_request(start, end, count, cooked, step);

  if (Py_None == date_format) {
    date_format = PyString_FromString("");
  }

  if (Py_None == file_obj || !PyFile_Check(file_obj)) {
    file_obj = PyString_FromString("stderr");
  }

  cdb = ((StorageObject*)self)->cdb;

  cdb_print_records(cdb, &request, PyFile_AsFile(file_obj), PyString_AsString(date_format));

  return self;
}
Exemplo n.º 8
0
static PyObject *Polygon_new(PyObject *self, PyObject *args) {
    PyObject *O = NULL, *TMP = NULL;
    int hole = 0;
    Polygon *p = Polygon_NEW(NULL);
    if (! PyArg_ParseTuple(args, "|Oi", &O, &hole))
        Polygon_Raise(ERR_ARG);
    if (O != NULL) {
        if ((PyTypeObject *)PyObject_Type(O) == &Polygon_Type) {
            if (poly_p_clone(((Polygon *)O)->p, p->p) != 0) {
                Polygon_dealloc(p);
                return Polygon_Raise(ERR_MEM);
            }
        } else if (PyString_Check(O)) {
            TMP = Polygon_read(p, args);
        } else if (PySequence_Check(O)) {
            TMP = Polygon_addContour(p, args);
        } else if (PyFile_Check(O)) {
            TMP = Polygon_read(p, args);
        } else return Polygon_Raise(ERR_ARG);
        if (TMP) Py_DECREF(TMP);
        if (PyErr_Occurred()) {
            Polygon_dealloc(p);
            return NULL;
        }
    }
    return (PyObject *)p;
}
Exemplo n.º 9
0
static int igraphmodule_i_filehandle_init_pypy_2(igraphmodule_filehandle_t* handle,
        PyObject* object, char* mode) {
    int fp;
    PyObject* fpobj;
    char* fname;

    if (object == 0 ||
        (!PyBaseString_Check(object) && !PyFile_Check(object))) {
        PyErr_SetString(PyExc_TypeError, "string or file handle expected");
        return 1;
    }

    handle->need_close = 0;

    if (PyBaseString_Check(object)) {
        /* We have received a string; we need to open the file denoted by this
         * string now and mark that we opened the file ourselves (so we need
         * to close it when igraphmodule_filehandle_destroy is invoked). */
        handle->object = PyFile_FromString(PyString_AsString(object), mode);
        if (handle->object == 0) {
            /* Could not open the file; just return an error code because an
             * exception was raised already */
            return 1;
        }
        /* Remember that we need to close the file ourselves */
        handle->need_close = 1;
    } else {
        /* This is probably a file-like object; store a reference for it and
         * we will handle it later */
        handle->object = object;
        Py_INCREF(handle->object);
    }

    /* PyPy does not have PyFile_AsFile, so we will try to access the file
     * descriptor instead by calling its fileno() method and then opening the
     * file handle with fdopen */
    fpobj = PyObject_CallMethod(handle->object, "fileno", 0);
    if (fpobj == 0 || !PyInt_Check(fpobj)) {
        if (fpobj != 0) {
            Py_DECREF(fpobj);
        }
        igraphmodule_filehandle_destroy(handle);
        /* This already called Py_DECREF(handle->object), no need to call it.
         * Also, an exception was raised by PyObject_CallMethod so no need to
         * raise one ourselves */
        return 1;
    }
    fp = (int)PyInt_AsLong(fpobj);
    Py_DECREF(fpobj);

    handle->fp = fdopen(fp, mode);
    if (handle->fp == 0) {
        igraphmodule_filehandle_destroy(handle);
        /* This already called Py_DECREF(handle->object), no need to call it */
        PyErr_SetString(PyExc_RuntimeError, "fdopen() failed unexpectedly");
        return 1;
    }

    return 0;
}
Exemplo n.º 10
0
/* Return an encoded file path, a file-like object or a NULL pointer.
 * May raise a Python error. Use PyErr_Occurred to check.
 */
static PyObject*
font_resource (const char *filename)
{
    PyObject* pkgdatamodule = NULL;
    PyObject* resourcefunc = NULL;
    PyObject* result = NULL;
    PyObject* tmp;

    pkgdatamodule = PyImport_ImportModule(pkgdatamodule_name);
    if (pkgdatamodule == NULL) {
        return NULL;
    }

    resourcefunc = PyObject_GetAttrString(pkgdatamodule, resourcefunc_name);
    Py_DECREF(pkgdatamodule);
    if (resourcefunc == NULL) {
        return NULL;
    }

    result = PyObject_CallFunction(resourcefunc, "s", filename);
    Py_DECREF(resourcefunc);
    if (result == NULL) {
        return NULL;
    }

#if PY3
    tmp = PyObject_GetAttrString(result, "name");
    if (tmp != NULL) {
        Py_DECREF(result);
        result = tmp;
    }
    else if (!PyErr_ExceptionMatches(PyExc_MemoryError)) {
        PyErr_Clear();
    }
#else
    if (PyFile_Check(result))
    {
        tmp = PyFile_Name(result);
        Py_INCREF(tmp);
        Py_DECREF(result);
        result = tmp;
    }
#endif

    tmp = RWopsEncodeFilePath(result, NULL);
    if (tmp == NULL) {
        Py_DECREF(result);
        return NULL;
    }
    else if (tmp != Py_None) {
        Py_DECREF(result);
        result = tmp;
    }
    else {
        Py_DECREF(tmp);
    }

    return result;
}
Exemplo n.º 11
0
PyObject *
PyFile_Name(PyObject *f)
{
	if (f == NULL || !PyFile_Check(f))
		return NULL;
	else
		return ((PyFileObject *)f)->f_name;
}
Exemplo n.º 12
0
FILE *
PyFile_AsFile(PyObject *f)
{
	if (f == NULL || !PyFile_Check(f))
		return NULL;
	else
		return ((PyFileObject *)f)->f_fp;
}
Exemplo n.º 13
0
static PyObject *PyStorage_new(PyObject *o, PyObject *_args) {
  try {
    PWOSequence args(_args);
    PyStorage *ps = 0;
    switch (args.len()) {
      case 0:
        ps = new PyStorage;
        break;
      case 1:
        if (!PyFile_Check((PyObject*)args[0])) {
          if (PyString_Check((PyObject*)args[0]))
            Fail(PyExc_TypeError, "rw parameter missing");
          else
            Fail(PyExc_TypeError, "argument not an open file");
          break;
        }
        ps = new PyStorage(*new c4_FileStrategy(PyFile_AsFile(args[0])), true);
        break;
      case 4:
         { // Rrrrrr...
          if (!PyStorage_Check((PyObject*)args[0]))
            Fail(PyExc_TypeError, "First arg must be a storage object");
          c4_Storage &storage = *(PyStorage*)(PyObject*)args[0];
          if (!PyView_Check((PyObject*)args[1]))
            Fail(PyExc_TypeError, "Second arg must be a view object");
          c4_View &view = *(PyView*)(PyObject*)args[1];
          if (!PyProperty_Check((PyObject*)args[2]))
            Fail(PyExc_TypeError, "Third arg must be a property object");
          c4_BytesProp &prop = *(c4_BytesProp*)(c4_Property*)(PyProperty*)
            (PyObject*)args[2];
          int row = PWONumber(args[3]);

          ps = new PyStorage(*new SiasStrategy(storage, view, prop, row), true);
          break;
        }
      case 2:
         {
          char *fnm;
          int mode;
          if (!PyArg_ParseTuple(args, "esi", "utf_8", &fnm, &mode))
            Fail(PyExc_TypeError, "bad argument type");
          ps = new PyStorage(fnm, mode);
          PyMem_Free(fnm);
          if (!ps->Strategy().IsValid()) {
            delete ps;
            ps = 0;
            Fail(PyExc_IOError, "can't open storage file");
          }
          break;
        }
      default:
        Fail(PyExc_ValueError, "storage() takes at most 4 arguments");
    }
    return ps;
  } catch (...) {
    return 0;
  }
}
Exemplo n.º 14
0
/**
 * \ingroup python_interface_filehandle
 * \brief Constructs a new file handle object from a Python object.
 *
 * \return 0 if everything was OK, 1 otherwise. An appropriate Python
 *   exception is raised in this case.
 */
int igraphmodule_filehandle_init(igraphmodule_filehandle_t* handle,
        PyObject* object, char* mode) {
#ifdef IGRAPH_PYTHON3
    int fp;
    if (object == 0 || PyLong_Check(object)) {
        PyErr_SetString(PyExc_TypeError, "string or file-like object expected");
        return 1;
    }
#else
    if (object == 0 ||
        (!PyBaseString_Check(object) && !PyFile_Check(object))) {
        PyErr_SetString(PyExc_TypeError, "string or file handle expected");
        return 1;
    }
#endif

    if (PyBaseString_Check(object)) {
#ifdef IGRAPH_PYTHON3
        handle->object = PyFile_FromObject(object, mode);
#else
        handle->object = PyFile_FromString(PyString_AsString(object), mode);
#endif
        if (handle->object == 0)
            return 1;
    } else {
        handle->object = object;
        Py_INCREF(handle->object);
    }

    /* At this stage, handle->object is something we can handle.
     * In Python 2, we get here only if object is a file object. In
     * Python 3, object can be anything, and PyFile_FromObject will
     * complain if the object cannot be converted to a file handle.
     */
#ifdef IGRAPH_PYTHON3
    fp = PyObject_AsFileDescriptor(handle->object);
    if (fp == -1) {
        Py_DECREF(handle->object);
        return 1;
    }
    handle->fp = fdopen(fp, mode);
    if (handle->fp == 0) {
        Py_DECREF(handle->object);
        PyErr_SetString(PyExc_RuntimeError, "fdopen() failed unexpectedly");
        return 1;
    }
#else
    handle->fp = PyFile_AsFile(handle->object);
    if (handle->fp == 0) {
        Py_DECREF(handle->object);
        PyErr_SetString(PyExc_RuntimeError, "PyFile_AsFile() failed unexpectedly");
        return 1;
    }
#endif

    return 0;
}
Exemplo n.º 15
0
static int
tok_stdin_decode(struct tok_state *tok, char **inp)
{
	PyObject *enc, *sysstdin, *decoded, *utf8;
	const char *encoding;
	char *converted;

	if (PySys_GetFile((char *)"stdin", NULL) != stdin)
		return 0;
	sysstdin = PySys_GetObject("stdin");
	if (sysstdin == NULL || !PyFile_Check(sysstdin))
		return 0;

	enc = ((PyFileObject *)sysstdin)->f_encoding;
	if (enc == NULL || !PyString_Check(enc))
		return 0;
	Py_INCREF(enc);

	encoding = PyString_AsString(enc);
	decoded = PyUnicode_Decode(*inp, strlen(*inp), 0, encoding, NULL);
	if (decoded == NULL)
		goto error_clear;

	utf8 = PyUnicode_AsEncodedString(decoded, "utf-8", NULL);
	Py_DECREF(decoded);
	if (utf8 == NULL)
		goto error_clear;

	assert(PyString_Check(utf8));
	converted = new_string(PyString_AS_STRING(utf8),
			       PyString_GET_SIZE(utf8));
	Py_DECREF(utf8);
	if (converted == NULL)
		goto error_nomem;

	PyMem_FREE(*inp);
	*inp = converted;
	if (tok->encoding != NULL)
		PyMem_FREE(tok->encoding);
	tok->encoding = new_string(encoding, strlen(encoding));
	if (tok->encoding == NULL)
		goto error_nomem;

	Py_DECREF(enc);
	return 0;

error_nomem:
	Py_DECREF(enc);
	tok->done = E_NOMEM;
	return -1;

error_clear:
	/* Fallback to iso-8859-1: for backward compatibility */
	Py_DECREF(enc);
	PyErr_Clear();
	return 0;
}
Exemplo n.º 16
0
extern "C" FILE* PySys_GetFile(char* name, FILE* def) noexcept {
    FILE* fp = NULL;
    PyObject* v = PySys_GetObject(name);
    if (v != NULL && PyFile_Check(v))
        fp = PyFile_AsFile(v);
    if (fp == NULL)
        fp = def;
    return fp;
}
Exemplo n.º 17
0
static SDL_RWops*
get_standard_rwop (PyObject* obj)
{
#if PY3
    if (PyUnicode_Check (obj)) {
        int result;
        char* name;
        PyObject* tuple = PyTuple_New (1);
        if (!tuple) {
            return NULL;
	}
        Py_INCREF (obj);
        PyTuple_SET_ITEM (tuple, 0, obj);
        result = PyArg_ParseTuple (tuple, "s", &name);
        Py_DECREF (tuple);
        if (!result)
            return NULL;
        return SDL_RWFromFile (name, "rb");
    }
    else if (PyBytes_Check (obj)) {
        int result;
        char* name;
        PyObject* tuple = PyTuple_New (1);
        if (!tuple)
            return NULL;
        Py_INCREF (obj);
        PyTuple_SET_ITEM (tuple, 0, obj);
        result = PyArg_ParseTuple (tuple, "y", &name);
        Py_DECREF (tuple);
        if (!result)
            return NULL;
        return SDL_RWFromFile (name, "rb");
    }
#else
    if (PyString_Check (obj) || PyUnicode_Check (obj))
    {
        int result;
        char* name;
        PyObject* tuple = PyTuple_New (1);
        if (!tuple)
            return NULL;
        Py_INCREF (obj);
        PyTuple_SET_ITEM (tuple, 0, obj);
        result = PyArg_ParseTuple (tuple, "s", &name);
        Py_DECREF (tuple);
        if (!result)
            return NULL;
        return SDL_RWFromFile (name, "rb");
    }
    else if (PyFile_Check(obj))
        return SDL_RWFromFP (PyFile_AsFile (obj), 0);
#endif
    return NULL;
}
Exemplo n.º 18
0
alignlib::HEncoder wrapper_for_load_Encoder( PyObject * fp )
      {
          if (!PyFile_Check(fp))
          {
              throw boost::python::error_already_set();
          }
         std::FILE * f = PyFile_AsFile(fp);   
         std_ibuf buf(f);
         std::istream is(&buf);
         if (is.peek() == EOF)
             return alignlib::HEncoder();
         else
             return alignlib::HEncoder (alignlib::loadEncoder( is ));
      }
Exemplo n.º 19
0
static PyObject*
FileWrapper_New(PyObject* self, PyObject* args, PyObject* kwargs)
{
  PyObject* file;
  if(!PyArg_ParseTuple(args, "O:FileWrapper", &file))
    return NULL;
  if(!PyFile_Check(file)) {
    TYPE_ERROR("FileWrapper argument", "file", file);
    return NULL;
  }
  Py_INCREF(file);
  FileWrapper* wrapper = PyObject_NEW(FileWrapper, &FileWrapper_Type);
  PyFile_IncUseCount((PyFileObject*)file);
  wrapper->file = file;
  return (PyObject*)wrapper;
}
Exemplo n.º 20
0
static PyObject *Polygon_read(Polygon *self, PyObject *args) {
    PyObject *O;
    int hflag = 1;
    if (! PyArg_ParseTuple(args, "O|i", &O, &hflag))
        return Polygon_Raise(ERR_ARG);
    if (PyFile_Check(O))
        gpc_read_polygon(PyFile_AsFile(O), hflag, self->gpc_p);
    else if (PyString_Check(O)) {
        FILE *f = fopen(PyString_AsString(O), "r");
        if (!f)
            return Polygon_Raise(PyExc_IOError, "Could not open file for reading!");
        gpc_read_polygon(f, hflag, self->gpc_p);
        fclose(f);
    } else
        return Polygon_Raise(ERR_ARG);
    Py_RETURN_NONE;
}
static PyObject *
image_read(PyObject *self,PyObject *args)
{
    PyObject *pyim;
    PyObject *pyFP;
    int file_type;
    if(!PyArg_ParseTuple(args,"OOi",&pyim,&pyFP,&file_type))
    {
	return NULL;
    }

    if(!PyFile_Check(pyFP))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

    FILE *fp = PyFile_AsFile(pyFP);

    if(!fp || !i)
    {
	PyErr_SetString(PyExc_ValueError, "Bad arguments");
	return NULL;
    }
    
    ImageReader *reader = ImageReader::create((image_file_t)file_type, fp, i);
    //if(!reader->ok())
    //{
    //	PyErr_SetString(PyExc_IOError, "Couldn't create image reader");
    //	delete reader;
    //	return NULL;
    //}

    if(!reader->read())
    {
	PyErr_SetString(PyExc_IOError, "Couldn't read image contents");
	delete reader;
	return NULL;
    }
    delete reader;

    Py_INCREF(Py_None);
    return Py_None;
}
Exemplo n.º 22
0
static bool
Command_redirect_iostream(twopence_command_t *cmd, twopence_iofd_t dst, PyObject *object, twopence_buf_t **buf_ret)
{
	if (object == NULL || PyByteArray_Check(object)) {
		twopence_buf_t *buffer;

		if (dst == TWOPENCE_STDIN && object == NULL)
			return true;

		/* Capture command output in a buffer */
		buffer = twopence_command_alloc_buffer(cmd, dst, 65536);
		twopence_command_ostream_capture(cmd, dst, buffer);
		if (dst == TWOPENCE_STDIN) {
			unsigned int count = PyByteArray_Size(object);

			twopence_buf_ensure_tailroom(buffer, count);
			twopence_buf_append(buffer, PyByteArray_AsString(object), count);
		}
		if (buf_ret)
			*buf_ret = buffer;
	} else
	if (PyFile_Check(object)) {
		int fd = PyObject_AsFileDescriptor(object);

		if (fd < 0) {
			/* If this fails, we could also pull the content into a buffer and then send that */
			PyErr_SetString(PyExc_TypeError, "unable to obtain file handle from File object");
			return false;
		}

		/* We dup() the file descriptor so that we no longer have to worry
		 * about what python does with its File object */
		twopence_command_iostream_redirect(cmd, dst, dup(fd), true);
	} else
	if (object == Py_None) {
		/* Nothing */
	} else {
		/* FIXME: we could check for a string type, and in that case interpret that as
		 * the name of a file to write to. */
		PyErr_SetString(PyExc_TypeError, "invalid type in stdio attribute");
		return false;
	}

	return true;
}
Exemplo n.º 23
0
static PyObject *Polygon_write(Polygon *self, PyObject *args) {
    PyObject *O;
    int hflag = 1;
    if (! PyArg_ParseTuple(args, "O|i", &O, &hflag))
        return Polygon_Raise(ERR_ARG);
    if (PyFile_Check(O))
        gpc_write_polygon(PyFile_AsFile(O), hflag, self->p);
    else if (PyString_Check(O)) {
        FILE *f = fopen(PyString_AsString(O), "w");
        if (!f)
            return Polygon_Raise(PyExc_IOError, "Could not open file for writing!");
        gpc_write_polygon(f, hflag, self->p);
        fclose(f);
    } else
        return Polygon_Raise(ERR_ARG);
    Py_INCREF(Py_None);
    return Py_None;
}
Exemplo n.º 24
0
static int igraphmodule_i_filehandle_init_cpython_2(igraphmodule_filehandle_t* handle,
        PyObject* object, char* mode) {
    if (object == 0 ||
        (!PyBaseString_Check(object) && !PyFile_Check(object))) {
        PyErr_SetString(PyExc_TypeError, "string or file handle expected");
        return 1;
    }

    handle->need_close = 0;

    if (PyBaseString_Check(object)) {
        /* We have received a string; we need to open the file denoted by this
         * string now and mark that we opened the file ourselves (so we need
         * to close it when igraphmodule_filehandle_destroy is invoked). */
        handle->object = PyFile_FromString(PyString_AsString(object), mode);
        if (handle->object == 0) {
            /* Could not open the file; just return an error code because an
             * exception was raised already */
            return 1;
        }
        /* Remember that we need to close the file ourselves */
        handle->need_close = 1;
    } else {
        /* This is probably a file-like object; store a reference for it and
         * we will handle it later */
        handle->object = object;
        Py_INCREF(handle->object);
    }

    /* At this stage, handle->object is something we can handle.
     * We get here only if object is a file object so we
     * can safely call PyFile_AsFile to get a FILE* object.
     */
    handle->fp = PyFile_AsFile(handle->object);
    if (handle->fp == 0) {
        igraphmodule_filehandle_destroy(handle);
        /* This already called Py_DECREF(handle->object), no need to call it */
        PyErr_SetString(PyExc_RuntimeError, "PyFile_AsFile() failed unexpectedly");
        return 1;
    }

    return 0;
}
Exemplo n.º 25
0
PyObject *py_uwsgi_sendfile(PyObject * self, PyObject * args) {

	struct wsgi_request *wsgi_req = current_wsgi_req(&uwsgi);

	if (!PyArg_ParseTuple(args, "Oi:uwsgi_sendfile", &wsgi_req->async_sendfile, &wsgi_req->sendfile_fd_chunk)) {
                return NULL;
        }

#ifdef PYTHREE
        wsgi_req->sendfile_fd = PyObject_AsFileDescriptor(wsgi_req->async_sendfile);
#else
        if (PyFile_Check((PyObject *)wsgi_req->async_sendfile)) {
		Py_INCREF((PyObject *)wsgi_req->async_sendfile);
                wsgi_req->sendfile_fd = PyObject_AsFileDescriptor(wsgi_req->async_sendfile);
        }
#endif


        return PyTuple_New(0);
}
Exemplo n.º 26
0
static PyObject *
fill_file_fields(PyFileObject *f, FILE *fp, char *name, char *mode,
		 int (*close)(FILE *))
{
	assert(f != NULL);
	assert(PyFile_Check(f));
	assert(f->f_fp == NULL);

	Py_DECREF(f->f_name);
	Py_DECREF(f->f_mode);
	f->f_name = PyString_FromString(name);
	f->f_mode = PyString_FromString(mode);

	f->f_close = close;
	f->f_softspace = 0;
	f->f_binary = strchr(mode,'b') != NULL;

	if (f->f_name == NULL || f->f_mode == NULL)
		return NULL;
	f->f_fp = fp;
	return (PyObject *) f;
}
Exemplo n.º 27
0
Arquivo: rpmmodule.c Projeto: xrg/RPM
static PyObject * setLogFile (PyObject * self, PyObject * args, PyObject *kwds)
{
    PyObject * fop = NULL;
    FILE * fp = NULL;
    char * kwlist[] = {"fileObject", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:logSetFile", kwlist, &fop))
	return NULL;

    if (fop) {
	if (!PyFile_Check(fop)) {
	    PyErr_SetString(pyrpmError, "requires file object");
	    return NULL;
	}
	fp = PyFile_AsFile(fop);
    }

    (void) rpmlogSetFile(fp);

    Py_INCREF(Py_None);
    return (PyObject *) Py_None;
}
Exemplo n.º 28
0
static PyObject *
dummy_decode_command2(PyObject *self, PyObject *args) {
  PyObject *po = PyTuple_GetItem(args, 0);
  if (!PyFile_Check(po)) {
    PyErr_SetString(DummyError, "First argument should be a file object.");
    return NULL;
  }
  hu::FileInStream stream;
  FILE *handle = PyFile_AsFile(po);
  stream.open(handle);
  
  int code = deserializeInt(stream);
  std::string key;
  std::string value;
  deserializeString(key, stream);
  deserializeString(value, stream);
  PyObject* res = PyTuple_New(3);
  PyTuple_SET_ITEM(res, 0, PyInt_FromLong(code));
  PyTuple_SET_ITEM(res, 1, PyString_FromStringAndSize(key.c_str(), key.size()));
  PyTuple_SET_ITEM(res, 2, PyString_FromStringAndSize(value.c_str(), value.size()));
  return res;
}
static PyObject *
image_writer_create(PyObject *self,PyObject *args)
{
    PyObject *pyim;
    PyObject *pyFP;
    int file_type;
    if(!PyArg_ParseTuple(args,"OOi",&pyim,&pyFP,&file_type))
    {
	return NULL;
    }

    if(!PyFile_Check(pyFP))
    {
	return NULL;
    }

    image *i = (image *)PyCObject_AsVoidPtr(pyim);

    FILE *fp = PyFile_AsFile(pyFP);

    if(!fp || !i)
    {
	PyErr_SetString(PyExc_ValueError, "Bad arguments");
	return NULL;
    }
    
    ImageWriter *writer = ImageWriter::create((image_file_t)file_type, fp, i);
    if(NULL == writer)
    {
	PyErr_SetString(PyExc_ValueError, "Unsupported file type");
	return NULL;
    }

    return PyCObject_FromVoidPtr(
	writer, (void (*)(void *))image_writer_delete);
}
Exemplo n.º 30
0
void setEncodingAndErrors() {
    // Adapted from pythonrun.c in CPython, with modifications for Pyston.

    char* p;
    char* icodeset = nullptr;
    char* codeset = nullptr;
    char* errors = nullptr;
    int free_codeset = 0;
    int overridden = 0;
    PyObject* sys_stream, *sys_isatty;
    char* saved_locale, *loc_codeset;

    if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
        p = icodeset = codeset = strdup(p);
        free_codeset = 1;
        errors = strchr(p, ':');
        if (errors) {
            *errors = '\0';
            errors++;
        }
        overridden = 1;
    }

#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
    /* On Unix, set the file system encoding according to the
       user's preference, if the CODESET names a well-known
       Python codec, and Py_FileSystemDefaultEncoding isn't
       initialized by other means. Also set the encoding of
       stdin and stdout if these are terminals, unless overridden.  */

    if (!overridden || !Py_FileSystemDefaultEncoding) {
        saved_locale = strdup(setlocale(LC_CTYPE, NULL));
        setlocale(LC_CTYPE, "");
        loc_codeset = nl_langinfo(CODESET);
        if (loc_codeset && *loc_codeset) {
            PyObject* enc = PyCodec_Encoder(loc_codeset);
            if (enc) {
                loc_codeset = strdup(loc_codeset);
                Py_DECREF(enc);
            } else {
                if (PyErr_ExceptionMatches(PyExc_LookupError)) {
                    PyErr_Clear();
                    loc_codeset = NULL;
                } else {
                    PyErr_Print();
                    exit(1);
                }
            }
        } else
            loc_codeset = NULL;
        setlocale(LC_CTYPE, saved_locale);
        free(saved_locale);

        if (!overridden) {
            codeset = icodeset = loc_codeset;
            free_codeset = 1;
        }

        /* Initialize Py_FileSystemDefaultEncoding from
           locale even if PYTHONIOENCODING is set. */
        if (!Py_FileSystemDefaultEncoding) {
            Py_FileSystemDefaultEncoding = loc_codeset;
            if (!overridden)
                free_codeset = 0;
        }
    }
#endif

#ifdef MS_WINDOWS
    if (!overridden) {
        icodeset = ibuf;
        codeset = buf;
        sprintf(ibuf, "cp%d", GetConsoleCP());
        sprintf(buf, "cp%d", GetConsoleOutputCP());
    }
#endif

    if (codeset) {
        sys_stream = PySys_GetObject("stdin");
        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
        if (!sys_isatty)
            PyErr_Clear();
        if ((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) {
            if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
                Py_FatalError("Cannot set codeset of stdin");
        }
        Py_XDECREF(sys_isatty);

        sys_stream = PySys_GetObject("stdout");
        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
        if (!sys_isatty)
            PyErr_Clear();
        if ((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) {
            if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
                Py_FatalError("Cannot set codeset of stdout");
        }
        Py_XDECREF(sys_isatty);

        sys_stream = PySys_GetObject("stderr");
        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
        if (!sys_isatty)
            PyErr_Clear();
        if ((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) {
            if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
                Py_FatalError("Cannot set codeset of stderr");
        }
        Py_XDECREF(sys_isatty);

        if (free_codeset)
            free(codeset);
    }
}