Oxygen reduction reaction (ORR) lies at the heart of many renewable energy technologies. Development of facile approaches toward highly active carbon materials for ORR is urgently desirable. We accidentally discovered a method for preparing heteroatom-doped carbon catalyst through an in situ self-templating and self-sacrificing strategy during the carbonization of a single polymer precursor. The prepared N,S co-doped and hierarchical porous carbon possesses a large specific surface area up to 2446 m2 g−1, which is the state-of-the-art among the porous carbons prepared by direct pyrolysis of linear polymer precursors. The use of in situ nanoarchitecturing and active-site engineering ensures that the N,S co-doped porous carbon catalyst has sufficient active sites for charge/mass transport and catalysis. As expected, as-prepared carbonaceous electrocatalyst exhibited superior ORR activity in both alkaline and acidic electrolytes and outperformed the state-of-the-art benchmark Pt/C and the best carbonaceous electrocatalysts for ORR in aqueous media so far. Moreover, the N,S co-doped carbon catalyst was demonstrated to be a highly efficient air cathode for Zn–air batteries. Thus, this study provides a new and economical method of fabricating feasible carbon electrocatalysts with exceptional catalytic activities for energy conversion and storage.