home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Python / sysmodule.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  20.0 KB  |  746 lines

  1.  
  2. /* System module */
  3.  
  4. /*
  5. Various bits of information used by the interpreter are collected in
  6. module 'sys'.
  7. Function member:
  8. - exit(sts): raise SystemExit
  9. Data members:
  10. - stdin, stdout, stderr: standard file objects
  11. - modules: the table of modules (dictionary)
  12. - path: module search path (list of strings)
  13. - argv: script arguments (list of strings)
  14. - ps1, ps2: optional primary and secondary prompts (strings)
  15. */
  16.  
  17. #include "Python.h"
  18.  
  19. #include "osdefs.h"
  20. #include "protos.h"
  21.  
  22. #ifdef HAVE_UNISTD_H
  23. #include <unistd.h>
  24. #endif
  25.  
  26. #ifdef MS_COREDLL
  27. extern void *PyWin_DLLhModule;
  28. /* A string loaded from the DLL at startup: */
  29. extern const char *PyWin_DLLVersionString;
  30. #endif
  31.  
  32. PyObject *
  33. PySys_GetObject(char *name)
  34. {
  35.     PyThreadState *tstate = PyThreadState_Get();
  36.     PyObject *sd = tstate->interp->sysdict;
  37.     if (sd == NULL)
  38.         return NULL;
  39.     return PyDict_GetItemString(sd, name);
  40. }
  41.  
  42. FILE *
  43. PySys_GetFile(char *name, FILE *def)
  44. {
  45.     FILE *fp = NULL;
  46.     PyObject *v = PySys_GetObject(name);
  47.     if (v != NULL && PyFile_Check(v))
  48.         fp = PyFile_AsFile(v);
  49.     if (fp == NULL)
  50.         fp = def;
  51.     return fp;
  52. }
  53.  
  54. int
  55. PySys_SetObject(char *name, PyObject *v)
  56. {
  57.     PyThreadState *tstate = PyThreadState_Get();
  58.     PyObject *sd = tstate->interp->sysdict;
  59.     if (v == NULL) {
  60.         if (PyDict_GetItemString(sd, name) == NULL)
  61.             return 0;
  62.         else
  63.             return PyDict_DelItemString(sd, name);
  64.     }
  65.     else
  66.         return PyDict_SetItemString(sd, name, v);
  67. }
  68.  
  69. static PyObject *
  70. sys_exc_info(PyObject *self, PyObject *args)
  71. {
  72.     PyThreadState *tstate;
  73.     if (!PyArg_ParseTuple(args, ":exc_info"))
  74.         return NULL;
  75.     tstate = PyThreadState_Get();
  76.     return Py_BuildValue(
  77.         "(OOO)",
  78.         tstate->exc_type != NULL ? tstate->exc_type : Py_None,
  79.         tstate->exc_value != NULL ? tstate->exc_value : Py_None,
  80.         tstate->exc_traceback != NULL ?
  81.             tstate->exc_traceback : Py_None);
  82. }
  83.  
  84. static char exc_info_doc[] =
  85. "exc_info() -> (type, value, traceback)\n\
  86. \n\
  87. Return information about the exception that is currently being handled.\n\
  88. This should be called from inside an except clause only.";
  89.  
  90. static PyObject *
  91. sys_exit(PyObject *self, PyObject *args)
  92. {
  93.     /* Raise SystemExit so callers may catch it or clean up. */
  94.     PyErr_SetObject(PyExc_SystemExit, args);
  95.     return NULL;
  96. }
  97.  
  98. static char exit_doc[] =
  99. "exit([status])\n\
  100. \n\
  101. Exit the interpreter by raising SystemExit(status).\n\
  102. If the status is omitted or None, it defaults to zero (i.e., success).\n\
  103. If the status numeric, it will be used as the system exit status.\n\
  104. If it is another kind of object, it will be printed and the system\n\
  105. exit status will be one (i.e., failure).";
  106.  
  107. static PyObject *
  108. sys_getdefaultencoding(PyObject *self, PyObject *args)
  109. {
  110.     if (!PyArg_ParseTuple(args, ":getdefaultencoding"))
  111.         return NULL;
  112.     return PyString_FromString(PyUnicode_GetDefaultEncoding());
  113. }
  114.  
  115. static char getdefaultencoding_doc[] =
  116. "getdefaultencoding() -> string\n\
  117. \n\
  118. Return the current default string encoding used by the Unicode \n\
  119. implementation.";
  120.  
  121. static PyObject *
  122. sys_setdefaultencoding(PyObject *self, PyObject *args)
  123. {
  124.     char *encoding;
  125.     if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
  126.         return NULL;
  127.     if (PyUnicode_SetDefaultEncoding(encoding))
  128.             return NULL;
  129.     Py_INCREF(Py_None);
  130.     return Py_None;
  131. }
  132.  
  133. static char setdefaultencoding_doc[] =
  134. "setdefaultencoding(encoding)\n\
  135. \n\
  136. Set the current default string encoding used by the Unicode implementation.";
  137.  
  138. static PyObject *
  139. sys_settrace(PyObject *self, PyObject *args)
  140. {
  141.     PyThreadState *tstate = PyThreadState_Get();
  142.     if (args == Py_None)
  143.         args = NULL;
  144.     else
  145.         Py_XINCREF(args);
  146.     Py_XDECREF(tstate->sys_tracefunc);
  147.     tstate->sys_tracefunc = args;
  148.     Py_INCREF(Py_None);
  149.     return Py_None;
  150. }
  151.  
  152. static char settrace_doc[] =
  153. "settrace(function)\n\
  154. \n\
  155. Set the global debug tracing function.  It will be called on each\n\
  156. function call.  See the debugger chapter in the library manual.";
  157.  
  158. static PyObject *
  159. sys_setprofile(PyObject *self, PyObject *args)
  160. {
  161.     PyThreadState *tstate = PyThreadState_Get();
  162.     if (args == Py_None)
  163.         args = NULL;
  164.     else
  165.         Py_XINCREF(args);
  166.     Py_XDECREF(tstate->sys_profilefunc);
  167.     tstate->sys_profilefunc = args;
  168.     Py_INCREF(Py_None);
  169.     return Py_None;
  170. }
  171.  
  172. static char setprofile_doc[] =
  173. "setprofile(function)\n\
  174. \n\
  175. Set the profiling function.  It will be called on each function call\n\
  176. and return.  See the profiler chapter in the library manual.";
  177.  
  178. static PyObject *
  179. sys_setcheckinterval(PyObject *self, PyObject *args)
  180. {
  181.     PyThreadState *tstate = PyThreadState_Get();
  182.     if (!PyArg_ParseTuple(args, "i:setcheckinterval", &tstate->interp->checkinterval))
  183.         return NULL;
  184.     Py_INCREF(Py_None);
  185.     return Py_None;
  186. }
  187.  
  188. static char setcheckinterval_doc[] =
  189. "setcheckinterval(n)\n\
  190. \n\
  191. Tell the Python interpreter to check for asynchronous events every\n\
  192. n instructions.  This also affects how often thread switches occur.";
  193.  
  194. static PyObject *
  195. sys_setrecursionlimit(PyObject *self, PyObject *args)
  196. {
  197.     int new_limit;
  198.     if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
  199.         return NULL;
  200.     if (new_limit <= 0) {
  201.         PyErr_SetString(PyExc_ValueError, 
  202.                 "recursion limit must be positive");  
  203.         return NULL;
  204.     }
  205.     Py_SetRecursionLimit(new_limit);
  206.     Py_INCREF(Py_None);
  207.     return Py_None;
  208. }
  209.  
  210. static char setrecursionlimit_doc[] =
  211. "setrecursionlimit(n)\n\
  212. \n\
  213. Set the maximum depth of the Python interpreter stack to n.  This\n\
  214. limit prevents infinite recursion from causing an overflow of the C\n\
  215. stack and crashing Python.  The highest possible limit is platform-\n\
  216. dependent.";
  217.  
  218. static PyObject *
  219. sys_getrecursionlimit(PyObject *self, PyObject *args)
  220. {
  221.     if (!PyArg_ParseTuple(args, ":getrecursionlimit"))
  222.         return NULL;
  223.     return PyInt_FromLong(Py_GetRecursionLimit());
  224. }
  225.  
  226. static char getrecursionlimit_doc[] =
  227. "getrecursionlimit()\n\
  228. \n\
  229. Return the current value of the recursion limit, the maximum depth\n\
  230. of the Python interpreter stack.  This limit prevents infinite\n\
  231. recursion from causing an overflow of the C stack and crashing Python.";
  232.  
  233. #ifdef USE_MALLOPT
  234. /* Link with -lmalloc (or -lmpc) on an SGI */
  235. #include <malloc.h>
  236.  
  237. static PyObject *
  238. sys_mdebug(PyObject *self, PyObject *args)
  239. {
  240.     int flag;
  241.     if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
  242.         return NULL;
  243.     mallopt(M_DEBUG, flag);
  244.     Py_INCREF(Py_None);
  245.     return Py_None;
  246. }
  247. #endif /* USE_MALLOPT */
  248.  
  249. static PyObject *
  250. sys_getrefcount(PyObject *self, PyObject *args)
  251. {
  252.     PyObject *arg;
  253.     if (!PyArg_ParseTuple(args, "O:getrefcount", &arg))
  254.         return NULL;
  255.     return PyInt_FromLong(arg->ob_refcnt);
  256. }
  257.  
  258. #ifdef Py_TRACE_REFS
  259. static PyObject *
  260. sys_gettotalrefcount(PyObject *self, PyObject *args)
  261. {
  262.     extern long _Py_RefTotal;
  263.     if (!PyArg_ParseTuple(args, ":gettotalrefcount"))
  264.         return NULL;
  265.     return PyInt_FromLong(_Py_RefTotal);
  266. }
  267.  
  268. #endif /* Py_TRACE_REFS */
  269.  
  270. static char getrefcount_doc[] =
  271. "getrefcount(object) -> integer\n\
  272. \n\
  273. Return the current reference count for the object.  This includes the\n\
  274. temporary reference in the argument list, so it is at least 2.";
  275.  
  276. #ifdef COUNT_ALLOCS
  277. static PyObject *
  278. sys_getcounts(PyObject *self, PyObject *args)
  279. {
  280.     extern PyObject *get_counts(void);
  281.  
  282.     if (!PyArg_ParseTuple(args, ":getcounts"))
  283.         return NULL;
  284.     return get_counts();
  285. }
  286. #endif
  287.  
  288. #ifdef Py_TRACE_REFS
  289. /* Defined in objects.c because it uses static globals if that file */
  290. extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
  291. #endif
  292.  
  293. #ifdef DYNAMIC_EXECUTION_PROFILE
  294. /* Defined in ceval.c because it uses static globals if that file */
  295. extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
  296. #endif
  297.  
  298. static PyMethodDef sys_methods[] = {
  299.     /* Might as well keep this in alphabetic order */
  300.     {"exc_info",    sys_exc_info, 1, exc_info_doc},
  301.     {"exit",    sys_exit, 0, exit_doc},
  302.     {"getdefaultencoding", sys_getdefaultencoding, 1,
  303.      getdefaultencoding_doc}, 
  304. #ifdef COUNT_ALLOCS
  305.     {"getcounts",    sys_getcounts, 1},
  306. #endif
  307. #ifdef DYNAMIC_EXECUTION_PROFILE
  308.     {"getdxp",    _Py_GetDXProfile, 1},
  309. #endif
  310. #ifdef Py_TRACE_REFS
  311.     {"getobjects",    _Py_GetObjects, 1},
  312.     {"gettotalrefcount", sys_gettotalrefcount, 1},
  313. #endif
  314.     {"getrefcount",    sys_getrefcount, 1, getrefcount_doc},
  315.     {"getrecursionlimit", sys_getrecursionlimit, 1,
  316.      getrecursionlimit_doc},
  317. #ifdef USE_MALLOPT
  318.     {"mdebug",    sys_mdebug, 1},
  319. #endif
  320.     {"setdefaultencoding", sys_setdefaultencoding, 1,
  321.      setdefaultencoding_doc}, 
  322.     {"setcheckinterval",    sys_setcheckinterval, 1,
  323.      setcheckinterval_doc}, 
  324.     {"setprofile",    sys_setprofile, 0, setprofile_doc},
  325.     {"setrecursionlimit", sys_setrecursionlimit, 1,
  326.      setrecursionlimit_doc},
  327.     {"settrace",    sys_settrace, 0, settrace_doc},
  328.     {NULL,        NULL}        /* sentinel */
  329. };
  330.  
  331. static PyObject *
  332. list_builtin_module_names(void)
  333. {
  334.     PyObject *list = PyList_New(0);
  335.     int i;
  336.     if (list == NULL)
  337.         return NULL;
  338.     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
  339.         PyObject *name = PyString_FromString(
  340.             PyImport_Inittab[i].name);
  341.         if (name == NULL)
  342.             break;
  343.         PyList_Append(list, name);
  344.         Py_DECREF(name);
  345.     }
  346.     if (PyList_Sort(list) != 0) {
  347.         Py_DECREF(list);
  348.         list = NULL;
  349.     }
  350.     if (list) {
  351.         PyObject *v = PyList_AsTuple(list);
  352.         Py_DECREF(list);
  353.         list = v;
  354.     }
  355.     return list;
  356. }
  357.  
  358. /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
  359.    Two literals concatenated works just fine.  If you have a K&R compiler
  360.    or other abomination that however *does* understand longer strings,
  361.    get rid of the !!! comment in the middle and the quotes that surround it. */
  362. static char sys_doc[] =
  363. "This module provides access to some objects used or maintained by the\n\
  364. interpreter and to functions that interact strongly with the interpreter.\n\
  365. \n\
  366. Dynamic objects:\n\
  367. \n\
  368. argv -- command line arguments; argv[0] is the script pathname if known\n\
  369. path -- module search path; path[0] is the script directory, else ''\n\
  370. modules -- dictionary of loaded modules\n\
  371. exitfunc -- you may set this to a function to be called when Python exits\n\
  372. \n\
  373. stdin -- standard input file object; used by raw_input() and input()\n\
  374. stdout -- standard output file object; used by the print statement\n\
  375. stderr -- standard error object; used for error messages\n\
  376.   By assigning another file object (or an object that behaves like a file)\n\
  377.   to one of these, it is possible to redirect all of the interpreter's I/O.\n\
  378. \n\
  379. last_type -- type of last uncaught exception\n\
  380. last_value -- value of last uncaught exception\n\
  381. last_traceback -- traceback of last uncaught exception\n\
  382.   These three are only available in an interactive session after a\n\
  383.   traceback has been printed.\n\
  384. \n\
  385. exc_type -- type of exception currently being handled\n\
  386. exc_value -- value of exception currently being handled\n\
  387. exc_traceback -- traceback of exception currently being handled\n\
  388.   The function exc_info() should be used instead of these three,\n\
  389.   because it is thread-safe.\n\
  390. "
  391. #ifndef MS_WIN16
  392. /* Concatenating string here */
  393. "\n\
  394. Static objects:\n\
  395. \n\
  396. maxint -- the largest supported integer (the smallest is -maxint-1)\n\
  397. builtin_module_names -- tuple of module names built into this intepreter\n\
  398. version -- the version of this interpreter as a string\n\
  399. version_info -- version information as a tuple\n\
  400. hexversion -- version information encoded as a single integer\n\
  401. copyright -- copyright notice pertaining to this interpreter\n\
  402. platform -- platform identifier\n\
  403. executable -- pathname of this Python interpreter\n\
  404. prefix -- prefix used to find the Python library\n\
  405. exec_prefix -- prefix used to find the machine-specific Python library\n\
  406. dllhandle -- [Windows only] integer handle of the Python DLL\n\
  407. winver -- [Windows only] version number of the Python DLL\n\
  408. __stdin__ -- the original stdin; don't use!\n\
  409. __stdout__ -- the original stdout; don't use!\n\
  410. __stderr__ -- the original stderr; don't use!\n\
  411. \n\
  412. Functions:\n\
  413. \n\
  414. exc_info() -- return thread-safe information about the current exception\n\
  415. exit() -- exit the interpreter by raising SystemExit\n\
  416. getrefcount() -- return the reference count for an object (plus one :-)\n\
  417. getrecursionlimit() -- return the max recursion depth for the interpreter\n\
  418. setcheckinterval() -- control how often the interpreter checks for events\n\
  419. setprofile() -- set the global profiling function\n\
  420. setrecursionlimit() -- set the max recursion depth for the interpreter\n\
  421. settrace() -- set the global debug tracing function\n\
  422. "
  423. #endif
  424. /* end of sys_doc */ ;
  425.  
  426. PyObject *
  427. _PySys_Init(void)
  428. {
  429.     PyObject *m, *v, *sysdict;
  430.     PyObject *sysin, *sysout, *syserr;
  431.     char *s;
  432.  
  433.     m = Py_InitModule3("sys", sys_methods, sys_doc);
  434.     sysdict = PyModule_GetDict(m);
  435.  
  436.     sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
  437.     sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
  438.     syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
  439.     if (PyErr_Occurred())
  440.         return NULL;
  441.     PyDict_SetItemString(sysdict, "stdin", sysin);
  442.     PyDict_SetItemString(sysdict, "stdout", sysout);
  443.     PyDict_SetItemString(sysdict, "stderr", syserr);
  444.     /* Make backup copies for cleanup */
  445.     PyDict_SetItemString(sysdict, "__stdin__", sysin);
  446.     PyDict_SetItemString(sysdict, "__stdout__", sysout);
  447.     PyDict_SetItemString(sysdict, "__stderr__", syserr);
  448.     Py_XDECREF(sysin);
  449.     Py_XDECREF(sysout);
  450.     Py_XDECREF(syserr);
  451.     PyDict_SetItemString(sysdict, "version",
  452.                  v = PyString_FromString(Py_GetVersion()));
  453.     Py_XDECREF(v);
  454.     PyDict_SetItemString(sysdict, "hexversion",
  455.                  v = PyInt_FromLong(PY_VERSION_HEX));
  456.     Py_XDECREF(v);
  457.     /*
  458.      * These release level checks are mutually exclusive and cover
  459.      * the field, so don't get too fancy with the pre-processor!
  460.      */
  461. #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
  462.     s = "alpha";
  463. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
  464.     s = "beta";
  465. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
  466.     s = "candidate";
  467. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
  468.     s = "final";
  469. #endif
  470.     PyDict_SetItemString(sysdict, "version_info",
  471.                  v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
  472.                            PY_MINOR_VERSION,
  473.                            PY_MICRO_VERSION, s,
  474.                            PY_RELEASE_SERIAL));
  475.     Py_XDECREF(v);
  476.     PyDict_SetItemString(sysdict, "copyright",
  477.                  v = PyString_FromString(Py_GetCopyright()));
  478.     Py_XDECREF(v);
  479.     PyDict_SetItemString(sysdict, "platform",
  480.                  v = PyString_FromString(Py_GetPlatform()));
  481.     Py_XDECREF(v);
  482.     PyDict_SetItemString(sysdict, "executable",
  483.                  v = PyString_FromString(Py_GetProgramFullPath()));
  484.     Py_XDECREF(v);
  485.     PyDict_SetItemString(sysdict, "prefix",
  486.                  v = PyString_FromString(Py_GetPrefix()));
  487.     Py_XDECREF(v);
  488.     PyDict_SetItemString(sysdict, "exec_prefix",
  489.            v = PyString_FromString(Py_GetExecPrefix()));
  490.     Py_XDECREF(v);
  491.     PyDict_SetItemString(sysdict, "maxint",
  492.                  v = PyInt_FromLong(PyInt_GetMax()));
  493.     Py_XDECREF(v);
  494.     PyDict_SetItemString(sysdict, "builtin_module_names",
  495.            v = list_builtin_module_names());
  496.     Py_XDECREF(v);
  497.     {
  498.         /* Assumes that longs are at least 2 bytes long.
  499.            Should be safe! */
  500.         unsigned long number = 1;
  501.         char *value;
  502.  
  503.         s = (char *) &number;
  504.         if (s[0] == 0)
  505.             value = "big";
  506.         else
  507.             value = "little";
  508.         PyDict_SetItemString(sysdict, "byteorder",
  509.                      v = PyString_FromString(value));
  510.         Py_XDECREF(v);
  511.     }
  512. #ifdef MS_COREDLL
  513.     PyDict_SetItemString(sysdict, "dllhandle",
  514.                  v = PyLong_FromVoidPtr(PyWin_DLLhModule));
  515.     Py_XDECREF(v);
  516.     PyDict_SetItemString(sysdict, "winver",
  517.                  v = PyString_FromString(PyWin_DLLVersionString));
  518.     Py_XDECREF(v);
  519. #endif
  520.     if (PyErr_Occurred())
  521.         return NULL;
  522.     return m;
  523. }
  524.  
  525. static PyObject *
  526. makepathobject(char *path, int delim)
  527. {
  528.     int i, n;
  529.     char *p;
  530.     PyObject *v, *w;
  531.     
  532.     n = 1;
  533.     p = path;
  534.     while ((p = strchr(p, delim)) != NULL) {
  535.         n++;
  536.         p++;
  537.     }
  538.     v = PyList_New(n);
  539.     if (v == NULL)
  540.         return NULL;
  541.     for (i = 0; ; i++) {
  542.         p = strchr(path, delim);
  543.         if (p == NULL)
  544.             p = strchr(path, '\0'); /* End of string */
  545.         w = PyString_FromStringAndSize(path, (int) (p - path));
  546.         if (w == NULL) {
  547.             Py_DECREF(v);
  548.             return NULL;
  549.         }
  550.         PyList_SetItem(v, i, w);
  551.         if (*p == '\0')
  552.             break;
  553.         path = p+1;
  554.     }
  555.     return v;
  556. }
  557.  
  558. void
  559. PySys_SetPath(char *path)
  560. {
  561.     PyObject *v;
  562.     if ((v = makepathobject(path, DELIM)) == NULL)
  563.         Py_FatalError("can't create sys.path");
  564.     if (PySys_SetObject("path", v) != 0)
  565.         Py_FatalError("can't assign sys.path");
  566.     Py_DECREF(v);
  567. }
  568.  
  569. static PyObject *
  570. makeargvobject(int argc, char **argv)
  571. {
  572.     PyObject *av;
  573.     if (argc <= 0 || argv == NULL) {
  574.         /* Ensure at least one (empty) argument is seen */
  575.         static char *empty_argv[1] = {""};
  576.         argv = empty_argv;
  577.         argc = 1;
  578.     }
  579.     av = PyList_New(argc);
  580.     if (av != NULL) {
  581.         int i;
  582.         for (i = 0; i < argc; i++) {
  583.             PyObject *v = PyString_FromString(argv[i]);
  584.             if (v == NULL) {
  585.                 Py_DECREF(av);
  586.                 av = NULL;
  587.                 break;
  588.             }
  589.             PyList_SetItem(av, i, v);
  590.         }
  591.     }
  592.     return av;
  593. }
  594.  
  595. void
  596. PySys_SetArgv(int argc, char **argv)
  597. {
  598.     PyObject *av = makeargvobject(argc, argv);
  599.     PyObject *path = PySys_GetObject("path");
  600.     if (av == NULL)
  601.         Py_FatalError("no mem for sys.argv");
  602.     if (PySys_SetObject("argv", av) != 0)
  603.         Py_FatalError("can't assign sys.argv");
  604.     if (path != NULL) {
  605.         char *argv0 = argv[0];
  606.         char *p = NULL;
  607.         int n = 0;
  608.         PyObject *a;
  609. #ifdef HAVE_READLINK
  610.         char link[MAXPATHLEN+1];
  611.         char argv0copy[2*MAXPATHLEN+1];
  612.         int nr = 0;
  613.         if (argc > 0 && argv0 != NULL)
  614.             nr = readlink(argv0, link, MAXPATHLEN);
  615.         if (nr > 0) {
  616.             /* It's a symlink */
  617.             link[nr] = '\0';
  618.             if (link[0] == SEP)
  619.                 argv0 = link; /* Link to absolute path */
  620.             else if (strchr(link, SEP) == NULL)
  621.                 ; /* Link without path */
  622.             else {
  623.                 /* Must join(dirname(argv0), link) */
  624.                 char *q = strrchr(argv0, SEP);
  625.                 if (q == NULL)
  626.                     argv0 = link; /* argv0 without path */
  627.                 else {
  628.                     /* Must make a copy */
  629.                     strcpy(argv0copy, argv0);
  630.                     q = strrchr(argv0copy, SEP);
  631.                     strcpy(q+1, link);
  632.                     argv0 = argv0copy;
  633.                 }
  634.             }
  635.         }
  636. #endif /* HAVE_READLINK */
  637. #if SEP == '\\' /* Special case for MS filename syntax */
  638.         if (argc > 0 && argv0 != NULL) {
  639.             char *q;
  640.             p = strrchr(argv0, SEP);
  641.             /* Test for alternate separator */
  642.             q = strrchr(p ? p : argv0, '/');
  643.             if (q != NULL)
  644.                 p = q;
  645.             if (p != NULL) {
  646.                 n = p + 1 - argv0;
  647.                 if (n > 1 && p[-1] != ':')
  648.                     n--; /* Drop trailing separator */
  649.             }
  650.         }
  651. #else /* All other filename syntaxes */
  652.         if (argc > 0 && argv0 != NULL)
  653.             p = strrchr(argv0, SEP);
  654.         if (p != NULL) {
  655.             n = p + 1 - argv0;
  656. #if SEP == '/' /* Special case for Unix filename syntax */
  657.             if (n > 1)
  658.                 n--; /* Drop trailing separator */
  659. #endif /* Unix */
  660.         }
  661. #ifdef _AMIGA
  662.         else
  663.         {
  664.             /* check for absolute paths on Amiga */
  665.             if(argc>0 && argv0!=NULL) p=strrchr(argv0,':');
  666.             if(p!=NULL)     n=p+1-argv0;
  667.         }
  668. #endif /* _AMIGA */
  669. #endif /* All others */
  670.         a = PyString_FromStringAndSize(argv0, n);
  671.         if (a == NULL)
  672.             Py_FatalError("no mem for sys.path insertion");
  673.         if (PyList_Insert(path, 0, a) < 0)
  674.             Py_FatalError("sys.path.insert(0) failed");
  675.         Py_DECREF(a);
  676.     }
  677.     Py_DECREF(av);
  678. }
  679.  
  680.  
  681. /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
  682.    Adapted from code submitted by Just van Rossum.
  683.  
  684.    PySys_WriteStdout(format, ...)
  685.    PySys_WriteStderr(format, ...)
  686.  
  687.       The first function writes to sys.stdout; the second to sys.stderr.  When
  688.       there is a problem, they write to the real (C level) stdout or stderr;
  689.       no exceptions are raised.
  690.  
  691.       Both take a printf-style format string as their first argument followed
  692.       by a variable length argument list determined by the format string.
  693.  
  694.       *** WARNING ***
  695.  
  696.       The format should limit the total size of the formatted output string to
  697.       1000 bytes.  In particular, this means that no unrestricted "%s" formats
  698.       should occur; these should be limited using "%.<N>s where <N> is a
  699.       decimal number calculated so that <N> plus the maximum size of other
  700.       formatted text does not exceed 1000 bytes.  Also watch out for "%f",
  701.       which can print hundreds of digits for very large numbers.
  702.  
  703.  */
  704.  
  705. static void
  706. mywrite(char *name, FILE *fp, const char *format, va_list va)
  707. {
  708.     PyObject *file;
  709.     PyObject *error_type, *error_value, *error_traceback;
  710.  
  711.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  712.     file = PySys_GetObject(name);
  713.     if (file == NULL || PyFile_AsFile(file) == fp)
  714.         vfprintf(fp, format, va);
  715.     else {
  716.         char buffer[1001];
  717.         if (vsprintf(buffer, format, va) >= sizeof(buffer))
  718.             Py_FatalError("PySys_WriteStdout/err: buffer overrun");
  719.         if (PyFile_WriteString(buffer, file) != 0) {
  720.             PyErr_Clear();
  721.             fputs(buffer, fp);
  722.         }
  723.     }
  724.     PyErr_Restore(error_type, error_value, error_traceback);
  725. }
  726.  
  727. void
  728. PySys_WriteStdout(const char *format, ...)
  729. {
  730.     va_list va;
  731.  
  732.     va_start(va, format);
  733.     mywrite("stdout", stdout, format, va);
  734.     va_end(va);
  735. }
  736.  
  737. void
  738. PySys_WriteStderr(const char *format, ...)
  739. {
  740.     va_list va;
  741.  
  742.     va_start(va, format);
  743.     mywrite("stderr", stderr, format, va);
  744.     va_end(va);
  745. }
  746.