1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
/*
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Routines common to all platforms.
*/
#include <Python.h>
#include <stdio.h>
// Global vars.
int PSUTIL_DEBUG = 0;
int PSUTIL_TESTING = 0;
/*
* Backport of unicode FS APIs from Python 3.
* On Python 2 we just return a plain byte string
* which is never supposed to raise decoding errors.
* See: https://github.com/giampaolo/psutil/issues/1040
*/
#if PY_MAJOR_VERSION < 3
PyObject *
PyUnicode_DecodeFSDefault(char *s) {
return PyString_FromString(s);
}
PyObject *
PyUnicode_DecodeFSDefaultAndSize(char *s, Py_ssize_t size) {
return PyString_FromStringAndSize(s, size);
}
#endif
/*
* Set OSError(errno=ESRCH, strerror="No such process") Python exception.
* If msg != "" the exception message will change in accordance.
*/
PyObject *
NoSuchProcess(char *msg) {
PyObject *exc;
exc = PyObject_CallFunction(
PyExc_OSError, "(is)", ESRCH, strlen(msg) ? msg : strerror(ESRCH));
PyErr_SetObject(PyExc_OSError, exc);
Py_XDECREF(exc);
return NULL;
}
/*
* Set OSError(errno=EACCES, strerror="Permission denied") Python exception.
* If msg != "" the exception message will change in accordance.
*/
PyObject *
AccessDenied(char *msg) {
PyObject *exc;
exc = PyObject_CallFunction(
PyExc_OSError, "(is)", EACCES, strlen(msg) ? msg : strerror(EACCES));
PyErr_SetObject(PyExc_OSError, exc);
Py_XDECREF(exc);
return NULL;
}
/*
* Enable testing mode. This has the same effect as setting PSUTIL_TESTING
* env var. This dual method exists because updating os.environ on
* Windows has no effect. Called on unit tests setup.
*/
PyObject *
psutil_set_testing(PyObject *self, PyObject *args) {
PSUTIL_TESTING = 1;
Py_INCREF(Py_None);
return Py_None;
}
/*
* Print a debug message on stderr. No-op if PSUTIL_DEBUG env var is not set.
*/
void
psutil_debug(const char* format, ...) {
va_list argptr;
va_start(argptr, format);
fprintf(stderr, "psutil-dubug> ");
vfprintf(stderr, format, argptr);
fprintf(stderr, "\n");
va_end(argptr);
}
/*
* Called on module import on all platforms.
*/
void
psutil_setup(void) {
if (getenv("PSUTIL_DEBUG") != NULL)
PSUTIL_DEBUG = 1;
if (getenv("PSUTIL_TESTING") != NULL)
PSUTIL_TESTING = 1;
}
|