comparison Python/pythonrun.c @ 15738:76caf0855d1f legacy-trunk

Recognize pyc files even if they don't end in pyc. Patch #103067 with modifications as discussed in email.
author Martin v. Löwis <martin@v.loewis.de>
date Thu, 04 Jan 2001 20:30:56 +0000
parents 37397bd1f8a8
children 0a77013c50ac
comparison
equal deleted inserted replaced
15737:27290eb9c526 15738:76caf0855d1f
544 PyRun_SimpleFile(FILE *fp, char *filename) 544 PyRun_SimpleFile(FILE *fp, char *filename)
545 { 545 {
546 return PyRun_SimpleFileEx(fp, filename, 0); 546 return PyRun_SimpleFileEx(fp, filename, 0);
547 } 547 }
548 548
549 /* Check whether a file maybe a pyc file: Look at the extension,
550 the file type, and, if we may close it, at the first few bytes. */
551
552 static int
553 maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
554 {
555 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
556 return 1;
557
558 #ifdef macintosh
559 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
560 if (PyMac_getfiletype(filename) == 'PYC '
561 || PyMac_getfiletype(filename) == 'APPL')
562 return 1;
563 #endif /* macintosh */
564
565 /* Only look into the file if we are allowed to close it, since
566 it then should also be seekable. */
567 if (closeit) {
568 /* Read only two bytes of the magic. If the file was opened in
569 text mode, the bytes 3 and 4 of the magic (\r\n) might not
570 be read as they are on disk. */
571 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
572 unsigned char buf[2];
573 if (fread(buf, 1, 2, fp) == 2
574 && (buf[1]<<8 | buf[0]) == halfmagic)
575 return 1;
576 fseek(fp, 0, SEEK_SET);
577 }
578 return 0;
579 }
580
549 int 581 int
550 PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit) 582 PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
551 { 583 {
552 PyObject *m, *d, *v; 584 PyObject *m, *d, *v;
553 char *ext; 585 char *ext;
555 m = PyImport_AddModule("__main__"); 587 m = PyImport_AddModule("__main__");
556 if (m == NULL) 588 if (m == NULL)
557 return -1; 589 return -1;
558 d = PyModule_GetDict(m); 590 d = PyModule_GetDict(m);
559 ext = filename + strlen(filename) - 4; 591 ext = filename + strlen(filename) - 4;
560 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0 592 if (maybe_pyc_file(fp, filename, ext, closeit)) {
561 #ifdef macintosh
562 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
563 || PyMac_getfiletype(filename) == 'PYC '
564 || PyMac_getfiletype(filename) == 'APPL'
565 #endif /* macintosh */
566 ) {
567 /* Try to run a pyc file. First, re-open in binary */ 593 /* Try to run a pyc file. First, re-open in binary */
568 if (closeit) 594 if (closeit)
569 fclose(fp); 595 fclose(fp);
570 if( (fp = fopen(filename, "rb")) == NULL ) { 596 if( (fp = fopen(filename, "rb")) == NULL ) {
571 fprintf(stderr, "python: Can't reopen .pyc file\n"); 597 fprintf(stderr, "python: Can't reopen .pyc file\n");