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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755
|
:mod:`!os` --- Miscellaneous operating system interfaces
========================================================
.. module:: os
:synopsis: Miscellaneous operating system interfaces.
**Source code:** :source:`Lib/os.py`
--------------
This module provides a portable way of using operating system dependent
functionality. If you just want to read or write a file see :func:`open`, if
you want to manipulate paths, see the :mod:`os.path` module, and if you want to
read all the lines in all the files on the command line see the :mod:`fileinput`
module. For creating temporary files and directories see the :mod:`tempfile`
module, and for high-level file and directory handling see the :mod:`shutil`
module.
Notes on the availability of these functions:
* The design of all built-in operating system dependent modules of Python is
such that as long as the same functionality is available, it uses the same
interface; for example, the function ``os.stat(path)`` returns stat
information about *path* in the same format (which happens to have originated
with the POSIX interface).
* Extensions peculiar to a particular operating system are also available
through the :mod:`os` module, but using them is of course a threat to
portability.
* All functions accepting path or file names accept both bytes and string
objects, and result in an object of the same type, if a path or file name is
returned.
* On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.
* On WebAssembly platforms, Android and iOS, large parts of the :mod:`os` module are
not available or behave differently. APIs related to processes (e.g.
:func:`~os.fork`, :func:`~os.execve`) and resources (e.g. :func:`~os.nice`)
are not available. Others like :func:`~os.getuid` and :func:`~os.getpid` are
emulated or stubs. WebAssembly platforms also lack support for signals (e.g.
:func:`~os.kill`, :func:`~os.wait`).
.. note::
All functions in this module raise :exc:`OSError` (or subclasses thereof) in
the case of invalid or inaccessible file names and paths, or other arguments
that have the correct type, but are not accepted by the operating system.
.. exception:: error
An alias for the built-in :exc:`OSError` exception.
.. data:: name
The name of the operating system dependent module imported. The following
names have currently been registered: ``'posix'``, ``'nt'``,
``'java'``.
.. seealso::
:data:`sys.platform` has a finer granularity. :func:`os.uname` gives
system-dependent version information.
The :mod:`platform` module provides detailed checks for the
system's identity.
.. _os-filenames:
.. _filesystem-encoding:
File Names, Command Line Arguments, and Environment Variables
-------------------------------------------------------------
In Python, file names, command line arguments, and environment variables are
represented using the string type. On some systems, decoding these strings to
and from bytes is necessary before passing them to the operating system. Python
uses the :term:`filesystem encoding and error handler` to perform this
conversion (see :func:`sys.getfilesystemencoding`).
The :term:`filesystem encoding and error handler` are configured at Python
startup by the :c:func:`PyConfig_Read` function: see
:c:member:`~PyConfig.filesystem_encoding` and
:c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
.. versionchanged:: 3.1
On some systems, conversion using the file system encoding may fail. In this
case, Python uses the :ref:`surrogateescape encoding error handler
<surrogateescape>`, which means that undecodable bytes are replaced by a
Unicode character U+DC\ *xx* on decoding, and these are again
translated to the original byte on encoding.
The :term:`file system encoding <filesystem encoding and error handler>` must
guarantee to successfully decode all bytes below 128. If the file system
encoding fails to provide this guarantee, API functions can raise
:exc:`UnicodeError`.
See also the :term:`locale encoding`.
.. _utf8-mode:
Python UTF-8 Mode
-----------------
.. versionadded:: 3.7
See :pep:`540` for more details.
The Python UTF-8 Mode ignores the :term:`locale encoding` and forces the usage
of the UTF-8 encoding:
* Use UTF-8 as the :term:`filesystem encoding <filesystem encoding and error
handler>`.
* :func:`sys.getfilesystemencoding` returns ``'utf-8'``.
* :func:`locale.getpreferredencoding` returns ``'utf-8'`` (the *do_setlocale*
argument has no effect).
* :data:`sys.stdin`, :data:`sys.stdout`, and :data:`sys.stderr` all use
UTF-8 as their text encoding, with the ``surrogateescape``
:ref:`error handler <error-handlers>` being enabled for :data:`sys.stdin`
and :data:`sys.stdout` (:data:`sys.stderr` continues to use
``backslashreplace`` as it does in the default locale-aware mode)
* On Unix, :func:`os.device_encoding` returns ``'utf-8'`` rather than the
device encoding.
Note that the standard stream settings in UTF-8 mode can be overridden by
:envvar:`PYTHONIOENCODING` (just as they can be in the default locale-aware
mode).
As a consequence of the changes in those lower level APIs, other higher
level APIs also exhibit different default behaviours:
* Command line arguments, environment variables and filenames are decoded
to text using the UTF-8 encoding.
* :func:`os.fsdecode` and :func:`os.fsencode` use the UTF-8 encoding.
* :func:`open`, :func:`io.open`, and :func:`codecs.open` use the UTF-8
encoding by default. However, they still use the strict error handler by
default so that attempting to open a binary file in text mode is likely
to raise an exception rather than producing nonsense data.
The :ref:`Python UTF-8 Mode <utf8-mode>` is enabled if the LC_CTYPE locale is
``C`` or ``POSIX`` at Python startup (see the :c:func:`PyConfig_Read`
function).
It can be enabled or disabled using the :option:`-X utf8 <-X>` command line
option and the :envvar:`PYTHONUTF8` environment variable.
If the :envvar:`PYTHONUTF8` environment variable is not set at all, then the
interpreter defaults to using the current locale settings, *unless* the current
locale is identified as a legacy ASCII-based locale (as described for
:envvar:`PYTHONCOERCECLOCALE`), and locale coercion is either disabled or
fails. In such legacy locales, the interpreter will default to enabling UTF-8
mode unless explicitly instructed not to do so.
The Python UTF-8 Mode can only be enabled at the Python startup. Its value
can be read from :data:`sys.flags.utf8_mode <sys.flags>`.
See also the :ref:`UTF-8 mode on Windows <win-utf8-mode>`
and the :term:`filesystem encoding and error handler`.
.. seealso::
:pep:`686`
Python 3.15 will make :ref:`utf8-mode` default.
.. _os-procinfo:
Process Parameters
------------------
These functions and data items provide information and operate on the current
process and user.
.. function:: ctermid()
Return the filename corresponding to the controlling terminal of the process.
.. availability:: Unix, not WASI.
.. data:: environ
A :term:`mapping` object where keys and values are strings that represent
the process environment. For example, ``environ['HOME']`` is the pathname
of your home directory (on some platforms), and is equivalent to
``getenv("HOME")`` in C.
This mapping is captured the first time the :mod:`os` module is imported,
typically during Python startup as part of processing :file:`site.py`. Changes
to the environment made after this time are not reflected in :data:`os.environ`,
except for changes made by modifying :data:`os.environ` directly.
This mapping may be used to modify the environment as well as query the
environment. :func:`putenv` will be called automatically when the mapping
is modified.
On Unix, keys and values use :func:`sys.getfilesystemencoding` and
``'surrogateescape'`` error handler. Use :data:`environb` if you would like
to use a different encoding.
On Windows, the keys are converted to uppercase. This also applies when
getting, setting, or deleting an item. For example,
``environ['monty'] = 'python'`` maps the key ``'MONTY'`` to the value
``'python'``.
.. note::
Calling :func:`putenv` directly does not change :data:`os.environ`, so it's better
to modify :data:`os.environ`.
.. note::
On some platforms, including FreeBSD and macOS, setting ``environ`` may
cause memory leaks. Refer to the system documentation for
:c:func:`!putenv`.
You can delete items in this mapping to unset environment variables.
:func:`unsetenv` will be called automatically when an item is deleted from
:data:`os.environ`, and when one of the :meth:`pop` or :meth:`clear` methods is
called.
.. versionchanged:: 3.9
Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
.. data:: environb
Bytes version of :data:`environ`: a :term:`mapping` object where both keys
and values are :class:`bytes` objects representing the process environment.
:data:`environ` and :data:`environb` are synchronized (modifying
:data:`environb` updates :data:`environ`, and vice versa).
:data:`environb` is only available if :const:`supports_bytes_environ` is
``True``.
.. versionadded:: 3.2
.. versionchanged:: 3.9
Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
.. function:: chdir(path)
fchdir(fd)
getcwd()
:noindex:
These functions are described in :ref:`os-file-dir`.
.. function:: fsencode(filename)
Encode :term:`path-like <path-like object>` *filename* to the
:term:`filesystem encoding and error handler`; return :class:`bytes`
unchanged.
:func:`fsdecode` is the reverse function.
.. versionadded:: 3.2
.. versionchanged:: 3.6
Support added to accept objects implementing the :class:`os.PathLike`
interface.
.. function:: fsdecode(filename)
Decode the :term:`path-like <path-like object>` *filename* from the
:term:`filesystem encoding and error handler`; return :class:`str`
unchanged.
:func:`fsencode` is the reverse function.
.. versionadded:: 3.2
.. versionchanged:: 3.6
Support added to accept objects implementing the :class:`os.PathLike`
interface.
.. function:: fspath(path)
Return the file system representation of the path.
If :class:`str` or :class:`bytes` is passed in, it is returned unchanged.
Otherwise :meth:`~os.PathLike.__fspath__` is called and its value is
returned as long as it is a :class:`str` or :class:`bytes` object.
In all other cases, :exc:`TypeError` is raised.
.. versionadded:: 3.6
.. class:: PathLike
An :term:`abstract base class` for objects representing a file system path,
e.g. :class:`pathlib.PurePath`.
.. versionadded:: 3.6
.. method:: __fspath__()
:abstractmethod:
Return the file system path representation of the object.
The method should only return a :class:`str` or :class:`bytes` object,
with the preference being for :class:`str`.
.. function:: getenv(key, default=None)
Return the value of the environment variable *key* as a string if it exists, or
*default* if it doesn't. *key* is a string. Note that
since :func:`getenv` uses :data:`os.environ`, the mapping of :func:`getenv` is
similarly also captured on import, and the function may not reflect
future environment changes.
On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
would like to use a different encoding.
.. availability:: Unix, Windows.
.. function:: getenvb(key, default=None)
Return the value of the environment variable *key* as bytes if it exists, or
*default* if it doesn't. *key* must be bytes. Note that
since :func:`getenvb` uses :data:`os.environb`, the mapping of :func:`getenvb` is
similarly also captured on import, and the function may not reflect
future environment changes.
:func:`getenvb` is only available if :const:`supports_bytes_environ`
is ``True``.
.. availability:: Unix.
.. versionadded:: 3.2
.. function:: get_exec_path(env=None)
Returns the list of directories that will be searched for a named
executable, similar to a shell, when launching a process.
*env*, when specified, should be an environment variable dictionary
to lookup the PATH in.
By default, when *env* is ``None``, :data:`environ` is used.
.. versionadded:: 3.2
.. function:: getegid()
Return the effective group id of the current process. This corresponds to the
"set id" bit on the file being executed in the current process.
.. availability:: Unix, not WASI.
.. function:: geteuid()
.. index:: single: user; effective id
Return the current process's effective user id.
.. availability:: Unix, not WASI.
.. function:: getgid()
.. index:: single: process; group
Return the real group id of the current process.
.. availability:: Unix.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: getgrouplist(user, group, /)
Return list of group ids that *user* belongs to. If *group* is not in the
list, it is included; typically, *group* is specified as the group ID
field from the password record for *user*, because that group ID will
otherwise be potentially omitted.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. function:: getgroups()
Return list of supplemental group ids associated with the current process.
.. availability:: Unix, not WASI.
.. note::
On macOS, :func:`getgroups` behavior differs somewhat from
other Unix platforms. If the Python interpreter was built with a
deployment target of ``10.5`` or earlier, :func:`getgroups` returns
the list of effective group ids associated with the current user process;
this list is limited to a system-defined number of entries, typically 16,
and may be modified by calls to :func:`setgroups` if suitably privileged.
If built with a deployment target greater than ``10.5``,
:func:`getgroups` returns the current group access list for the user
associated with the effective user id of the process; the group access
list may change over the lifetime of the process, it is not affected by
calls to :func:`setgroups`, and its length is not limited to 16. The
deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
obtained with :func:`sysconfig.get_config_var`.
.. function:: getlogin()
Return the name of the user logged in on the controlling terminal of the
process. For most purposes, it is more useful to use
:func:`getpass.getuser` since the latter checks the environment variables
:envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user is, and
falls back to ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the
current real user id.
.. availability:: Unix, Windows, not WASI.
.. function:: getpgid(pid)
Return the process group id of the process with process id *pid*. If *pid* is 0,
the process group id of the current process is returned.
.. availability:: Unix, not WASI.
.. function:: getpgrp()
.. index:: single: process; group
Return the id of the current process group.
.. availability:: Unix, not WASI.
.. function:: getpid()
.. index:: single: process; id
Return the current process id.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: getppid()
.. index:: single: process; id of parent
Return the parent's process id. When the parent process has exited, on Unix
the id returned is the one of the init process (1), on Windows it is still
the same id, which may be already reused by another process.
.. availability:: Unix, Windows, not WASI.
.. versionchanged:: 3.2
Added support for Windows.
.. function:: getpriority(which, who)
.. index:: single: process; scheduling priority
Get program scheduling priority. The value *which* is one of
:const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
is interpreted relative to *which* (a process identifier for
:const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
user ID for :const:`PRIO_USER`). A zero value for *who* denotes
(respectively) the calling process, the process group of the calling process,
or the real user ID of the calling process.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. data:: PRIO_PROCESS
PRIO_PGRP
PRIO_USER
Parameters for the :func:`getpriority` and :func:`setpriority` functions.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. data:: PRIO_DARWIN_THREAD
PRIO_DARWIN_PROCESS
PRIO_DARWIN_BG
PRIO_DARWIN_NONUI
Parameters for the :func:`getpriority` and :func:`setpriority` functions.
.. availability:: macOS
.. versionadded:: 3.12
.. function:: getresuid()
Return a tuple (ruid, euid, suid) denoting the current process's
real, effective, and saved user ids.
.. availability:: Unix, not WASI.
.. versionadded:: 3.2
.. function:: getresgid()
Return a tuple (rgid, egid, sgid) denoting the current process's
real, effective, and saved group ids.
.. availability:: Unix, not WASI.
.. versionadded:: 3.2
.. function:: getuid()
.. index:: single: user; id
Return the current process's real user id.
.. availability:: Unix.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: initgroups(username, gid, /)
Call the system initgroups() to initialize the group access list with all of
the groups of which the specified username is a member, plus the specified
group id.
.. availability:: Unix, not WASI, not Android.
.. versionadded:: 3.2
.. function:: putenv(key, value, /)
.. index:: single: environment variables; setting
Set the environment variable named *key* to the string *value*. Such
changes to the environment affect subprocesses started with :func:`os.system`,
:func:`popen` or :func:`fork` and :func:`execv`.
Assignments to items in :data:`os.environ` are automatically translated into
corresponding calls to :func:`putenv`; however, calls to :func:`putenv`
don't update :data:`os.environ`, so it is actually preferable to assign to items
of :data:`os.environ`. This also applies to :func:`getenv` and :func:`getenvb`, which
respectively use :data:`os.environ` and :data:`os.environb` in their implementations.
.. note::
On some platforms, including FreeBSD and macOS, setting ``environ`` may
cause memory leaks. Refer to the system documentation for :c:func:`!putenv`.
.. audit-event:: os.putenv key,value os.putenv
.. versionchanged:: 3.9
The function is now always available.
.. function:: setegid(egid, /)
Set the current process's effective group id.
.. availability:: Unix, not WASI, not Android.
.. function:: seteuid(euid, /)
Set the current process's effective user id.
.. availability:: Unix, not WASI, not Android.
.. function:: setgid(gid, /)
Set the current process' group id.
.. availability:: Unix, not WASI, not Android.
.. function:: setgroups(groups, /)
Set the list of supplemental group ids associated with the current process to
*groups*. *groups* must be a sequence, and each element must be an integer
identifying a group. This operation is typically available only to the superuser.
.. availability:: Unix, not WASI.
.. note:: On macOS, the length of *groups* may not exceed the
system-defined maximum number of effective group ids, typically 16.
See the documentation for :func:`getgroups` for cases where it may not
return the same group list set by calling setgroups().
.. function:: setns(fd, nstype=0)
Reassociate the current thread with a Linux namespace.
See the :manpage:`setns(2)` and :manpage:`namespaces(7)` man pages for more
details.
If *fd* refers to a :file:`/proc/{pid}/ns/` link, ``setns()`` reassociates the
calling thread with the namespace associated with that link,
and *nstype* may be set to one of the
:ref:`CLONE_NEW* constants <os-unshare-clone-flags>`
to impose constraints on the operation
(``0`` means no constraints).
Since Linux 5.8, *fd* may refer to a PID file descriptor obtained from
:func:`~os.pidfd_open`. In this case, ``setns()`` reassociates the calling thread
into one or more of the same namespaces as the thread referred to by *fd*.
This is subject to any constraints imposed by *nstype*,
which is a bit mask combining one or more of the
:ref:`CLONE_NEW* constants <os-unshare-clone-flags>`,
e.g. ``setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID)``.
The caller's memberships in unspecified namespaces are left unchanged.
*fd* can be any object with a :meth:`~io.IOBase.fileno` method, or a raw file descriptor.
This example reassociates the thread with the ``init`` process's network namespace::
fd = os.open("/proc/1/ns/net", os.O_RDONLY)
os.setns(fd, os.CLONE_NEWNET)
os.close(fd)
.. availability:: Linux >= 3.0 with glibc >= 2.14.
.. versionadded:: 3.12
.. seealso::
The :func:`~os.unshare` function.
.. function:: setpgrp()
Call the system call :c:func:`!setpgrp` or ``setpgrp(0, 0)`` depending on
which version is implemented (if any). See the Unix manual for the semantics.
.. availability:: Unix, not WASI.
.. function:: setpgid(pid, pgrp, /)
Call the system call :c:func:`!setpgid` to set the process group id of the
process with id *pid* to the process group with id *pgrp*. See the Unix manual
for the semantics.
.. availability:: Unix, not WASI.
.. function:: setpriority(which, who, priority)
.. index:: single: process; scheduling priority
Set program scheduling priority. The value *which* is one of
:const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
is interpreted relative to *which* (a process identifier for
:const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
user ID for :const:`PRIO_USER`). A zero value for *who* denotes
(respectively) the calling process, the process group of the calling process,
or the real user ID of the calling process.
*priority* is a value in the range -20 to 19. The default priority is 0;
lower priorities cause more favorable scheduling.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. function:: setregid(rgid, egid, /)
Set the current process's real and effective group ids.
.. availability:: Unix, not WASI, not Android.
.. function:: setresgid(rgid, egid, sgid, /)
Set the current process's real, effective, and saved group ids.
.. availability:: Unix, not WASI, not Android.
.. versionadded:: 3.2
.. function:: setresuid(ruid, euid, suid, /)
Set the current process's real, effective, and saved user ids.
.. availability:: Unix, not WASI, not Android.
.. versionadded:: 3.2
.. function:: setreuid(ruid, euid, /)
Set the current process's real and effective user ids.
.. availability:: Unix, not WASI, not Android.
.. function:: getsid(pid, /)
Call the system call :c:func:`!getsid`. See the Unix manual for the semantics.
.. availability:: Unix, not WASI.
.. function:: setsid()
Call the system call :c:func:`!setsid`. See the Unix manual for the semantics.
.. availability:: Unix, not WASI.
.. function:: setuid(uid, /)
.. index:: single: user; id, setting
Set the current process's user id.
.. availability:: Unix, not WASI, not Android.
.. placed in this section since it relates to errno.... a little weak
.. function:: strerror(code, /)
Return the error message corresponding to the error code in *code*.
On platforms where :c:func:`!strerror` returns ``NULL`` when given an unknown
error number, :exc:`ValueError` is raised.
.. data:: supports_bytes_environ
``True`` if the native OS type of the environment is bytes (eg. ``False`` on
Windows).
.. versionadded:: 3.2
.. function:: umask(mask, /)
Set the current numeric umask and return the previous umask.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: uname()
.. index::
single: gethostname() (in module socket)
single: gethostbyaddr() (in module socket)
Returns information identifying the current operating system.
The return value is an object with five attributes:
* :attr:`sysname` - operating system name
* :attr:`nodename` - name of machine on network (implementation-defined)
* :attr:`release` - operating system release
* :attr:`version` - operating system version
* :attr:`machine` - hardware identifier
For backwards compatibility, this object is also iterable, behaving
like a five-tuple containing :attr:`sysname`, :attr:`nodename`,
:attr:`release`, :attr:`version`, and :attr:`machine`
in that order.
Some systems truncate :attr:`nodename` to 8 characters or to the
leading component; a better way to get the hostname is
:func:`socket.gethostname` or even
``socket.gethostbyaddr(socket.gethostname())``.
On macOS, iOS and Android, this returns the *kernel* name and version (i.e.,
``'Darwin'`` on macOS and iOS; ``'Linux'`` on Android). :func:`platform.uname`
can be used to get the user-facing operating system name and version on iOS and
Android.
.. availability:: Unix.
.. versionchanged:: 3.3
Return type changed from a tuple to a tuple-like object
with named attributes.
.. function:: unsetenv(key, /)
.. index:: single: environment variables; deleting
Unset (delete) the environment variable named *key*. Such changes to the
environment affect subprocesses started with :func:`os.system`, :func:`popen` or
:func:`fork` and :func:`execv`.
Deletion of items in :data:`os.environ` is automatically translated into a
corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv`
don't update :data:`os.environ`, so it is actually preferable to delete items of
:data:`os.environ`.
.. audit-event:: os.unsetenv key os.unsetenv
.. versionchanged:: 3.9
The function is now always available and is also available on Windows.
.. function:: unshare(flags)
Disassociate parts of the process execution context, and move them into a
newly created namespace.
See the :manpage:`unshare(2)`
man page for more details.
The *flags* argument is a bit mask, combining zero or more of the
:ref:`CLONE_* constants <os-unshare-clone-flags>`,
that specifies which parts of the execution context should be
unshared from their existing associations and moved to a new namespace.
If the *flags* argument is ``0``, no changes are made to the calling process's
execution context.
.. availability:: Linux >= 2.6.16.
.. versionadded:: 3.12
.. seealso::
The :func:`~os.setns` function.
.. _os-unshare-clone-flags:
Flags to the :func:`unshare` function, if the implementation supports them.
See :manpage:`unshare(2)` in the Linux manual
for their exact effect and availability.
.. data:: CLONE_FILES
CLONE_FS
CLONE_NEWCGROUP
CLONE_NEWIPC
CLONE_NEWNET
CLONE_NEWNS
CLONE_NEWPID
CLONE_NEWTIME
CLONE_NEWUSER
CLONE_NEWUTS
CLONE_SIGHAND
CLONE_SYSVSEM
CLONE_THREAD
CLONE_VM
.. _os-newstreams:
File Object Creation
--------------------
These functions create new :term:`file objects <file object>`. (See also
:func:`~os.open` for opening file descriptors.)
.. function:: fdopen(fd, *args, **kwargs)
Return an open file object connected to the file descriptor *fd*. This is an
alias of the :func:`open` built-in function and accepts the same arguments.
The only difference is that the first argument of :func:`fdopen` must always
be an integer.
.. _os-fd-ops:
File Descriptor Operations
--------------------------
These functions operate on I/O streams referenced using file descriptors.
File descriptors are small integers corresponding to a file that has been opened
by the current process. For example, standard input is usually file descriptor
0, standard output is 1, and standard error is 2. Further files opened by a
process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
by file descriptors.
The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor
associated with a :term:`file object` when required. Note that using the file
descriptor directly will bypass the file object methods, ignoring aspects such
as internal buffering of data.
.. function:: close(fd)
Close file descriptor *fd*.
.. note::
This function is intended for low-level I/O and must be applied to a file
descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
object" returned by the built-in function :func:`open` or by :func:`popen` or
:func:`fdopen`, use its :meth:`~io.IOBase.close` method.
.. function:: closerange(fd_low, fd_high, /)
Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
ignoring errors. Equivalent to (but much faster than)::
for fd in range(fd_low, fd_high):
try:
os.close(fd)
except OSError:
pass
.. function:: copy_file_range(src, dst, count, offset_src=None, offset_dst=None)
Copy *count* bytes from file descriptor *src*, starting from offset
*offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
If *offset_src* is ``None``, then *src* is read from the current position;
respectively for *offset_dst*.
In Linux kernel older than 5.3, the files pointed to by *src* and *dst*
must reside in the same filesystem, otherwise an :exc:`OSError` is
raised with :attr:`~OSError.errno` set to :const:`errno.EXDEV`.
This copy is done without the additional cost of transferring data
from the kernel to user space and then back into the kernel. Additionally,
some filesystems could implement extra optimizations, such as the use of
reflinks (i.e., two or more inodes that share pointers to the same
copy-on-write disk blocks; supported file systems include btrfs and XFS)
and server-side copy (in the case of NFS).
The function copies bytes between two file descriptors. Text options, like
the encoding and the line ending, are ignored.
The return value is the amount of bytes copied. This could be less than the
amount requested.
.. note::
On Linux, :func:`os.copy_file_range` should not be used for copying a
range of a pseudo file from a special filesystem like procfs and sysfs.
It will always copy no bytes and return 0 as if the file was empty
because of a known Linux kernel issue.
.. availability:: Linux >= 4.5 with glibc >= 2.27.
.. versionadded:: 3.8
.. function:: device_encoding(fd)
Return a string describing the encoding of the device associated with *fd*
if it is connected to a terminal; else return :const:`None`.
On Unix, if the :ref:`Python UTF-8 Mode <utf8-mode>` is enabled, return
``'UTF-8'`` rather than the device encoding.
.. versionchanged:: 3.10
On Unix, the function now implements the Python UTF-8 Mode.
.. function:: dup(fd, /)
Return a duplicate of file descriptor *fd*. The new file descriptor is
:ref:`non-inheritable <fd_inheritance>`.
On Windows, when duplicating a standard stream (0: stdin, 1: stdout,
2: stderr), the new file descriptor is :ref:`inheritable
<fd_inheritance>`.
.. availability:: not WASI.
.. versionchanged:: 3.4
The new file descriptor is now non-inheritable.
.. function:: dup2(fd, fd2, inheritable=True)
Duplicate file descriptor *fd* to *fd2*, closing the latter first if
necessary. Return *fd2*. The new file descriptor is :ref:`inheritable
<fd_inheritance>` by default or non-inheritable if *inheritable*
is ``False``.
.. availability:: not WASI.
.. versionchanged:: 3.4
Add the optional *inheritable* parameter.
.. versionchanged:: 3.7
Return *fd2* on success. Previously, ``None`` was always returned.
.. function:: fchmod(fd, mode)
Change the mode of the file given by *fd* to the numeric *mode*. See the
docs for :func:`chmod` for possible values of *mode*. As of Python 3.3, this
is equivalent to ``os.chmod(fd, mode)``.
.. audit-event:: os.chmod path,mode,dir_fd os.fchmod
.. availability:: Unix, Windows.
The function is limited on WASI, see :ref:`wasm-availability` for more
information.
.. versionchanged:: 3.13
Added support on Windows.
.. function:: fchown(fd, uid, gid)
Change the owner and group id of the file given by *fd* to the numeric *uid*
and *gid*. To leave one of the ids unchanged, set it to -1. See
:func:`chown`. As of Python 3.3, this is equivalent to ``os.chown(fd, uid,
gid)``.
.. audit-event:: os.chown path,uid,gid,dir_fd os.fchown
.. availability:: Unix.
The function is limited on WASI, see :ref:`wasm-availability` for more
information.
.. function:: fdatasync(fd)
Force write of file with filedescriptor *fd* to disk. Does not force update of
metadata.
.. availability:: Unix.
.. note::
This function is not available on MacOS.
.. function:: fpathconf(fd, name, /)
Return system configuration information relevant to an open file. *name*
specifies the configuration value to retrieve; it may be a string which is the
name of a defined system value; these names are specified in a number of
standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
additional names as well. The names known to the host operating system are
given in the ``pathconf_names`` dictionary. For configuration variables not
included in that mapping, passing an integer for *name* is also accepted.
If *name* is a string and is not known, :exc:`ValueError` is raised. If a
specific value for *name* is not supported by the host system, even if it is
included in ``pathconf_names``, an :exc:`OSError` is raised with
:const:`errno.EINVAL` for the error number.
As of Python 3.3, this is equivalent to ``os.pathconf(fd, name)``.
.. availability:: Unix.
.. function:: fstat(fd)
Get the status of the file descriptor *fd*. Return a :class:`stat_result`
object.
As of Python 3.3, this is equivalent to ``os.stat(fd)``.
.. seealso::
The :func:`.stat` function.
.. function:: fstatvfs(fd, /)
Return information about the filesystem containing the file associated with
file descriptor *fd*, like :func:`statvfs`. As of Python 3.3, this is
equivalent to ``os.statvfs(fd)``.
.. availability:: Unix.
.. function:: fsync(fd)
Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
native :c:func:`!fsync` function; on Windows, the MS :c:func:`!_commit` function.
If you're starting with a buffered Python :term:`file object` *f*, first do
``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal
buffers associated with *f* are written to disk.
.. availability:: Unix, Windows.
.. function:: ftruncate(fd, length, /)
Truncate the file corresponding to file descriptor *fd*, so that it is at
most *length* bytes in size. As of Python 3.3, this is equivalent to
``os.truncate(fd, length)``.
.. audit-event:: os.truncate fd,length os.ftruncate
.. availability:: Unix, Windows.
.. versionchanged:: 3.5
Added support for Windows
.. function:: get_blocking(fd, /)
Get the blocking mode of the file descriptor: ``False`` if the
:data:`O_NONBLOCK` flag is set, ``True`` if the flag is cleared.
See also :func:`set_blocking` and :meth:`socket.socket.setblocking`.
.. availability:: Unix, Windows.
The function is limited on WASI, see :ref:`wasm-availability` for more
information.
On Windows, this function is limited to pipes.
.. versionadded:: 3.5
.. versionchanged:: 3.12
Added support for pipes on Windows.
.. function:: grantpt(fd, /)
Grant access to the slave pseudo-terminal device associated with the
master pseudo-terminal device to which the file descriptor *fd* refers.
The file descriptor *fd* is not closed upon failure.
Calls the C standard library function :c:func:`grantpt`.
.. availability:: Unix, not WASI.
.. versionadded:: 3.13
.. function:: isatty(fd, /)
Return ``True`` if the file descriptor *fd* is open and connected to a
tty(-like) device, else ``False``.
.. function:: lockf(fd, cmd, len, /)
Apply, test or remove a POSIX lock on an open file descriptor.
*fd* is an open file descriptor.
*cmd* specifies the command to use - one of :data:`F_LOCK`, :data:`F_TLOCK`,
:data:`F_ULOCK` or :data:`F_TEST`.
*len* specifies the section of the file to lock.
.. audit-event:: os.lockf fd,cmd,len os.lockf
.. availability:: Unix.
.. versionadded:: 3.3
.. data:: F_LOCK
F_TLOCK
F_ULOCK
F_TEST
Flags that specify what action :func:`lockf` will take.
.. availability:: Unix.
.. versionadded:: 3.3
.. function:: login_tty(fd, /)
Prepare the tty of which fd is a file descriptor for a new login session.
Make the calling process a session leader; make the tty the controlling tty,
the stdin, the stdout, and the stderr of the calling process; close fd.
.. availability:: Unix, not WASI.
.. versionadded:: 3.11
.. function:: lseek(fd, pos, whence, /)
Set the current position of file descriptor *fd* to position *pos*, modified
by *whence*, and return the new position in bytes relative to
the start of the file.
Valid values for *whence* are:
* :const:`SEEK_SET` or ``0`` -- set *pos* relative to the beginning of the file
* :const:`SEEK_CUR` or ``1`` -- set *pos* relative to the current file position
* :const:`SEEK_END` or ``2`` -- set *pos* relative to the end of the file
* :const:`SEEK_HOLE` -- set *pos* to the next data location, relative to *pos*
* :const:`SEEK_DATA` -- set *pos* to the next data hole, relative to *pos*
.. versionchanged:: 3.3
Add support for :const:`!SEEK_HOLE` and :const:`!SEEK_DATA`.
.. data:: SEEK_SET
SEEK_CUR
SEEK_END
Parameters to the :func:`lseek` function and the :meth:`~io.IOBase.seek`
method on :term:`file-like objects <file object>`,
for whence to adjust the file position indicator.
:const:`SEEK_SET`
Adjust the file position relative to the beginning of the file.
:const:`SEEK_CUR`
Adjust the file position relative to the current file position.
:const:`SEEK_END`
Adjust the file position relative to the end of the file.
Their values are 0, 1, and 2, respectively.
.. data:: SEEK_HOLE
SEEK_DATA
Parameters to the :func:`lseek` function and the :meth:`~io.IOBase.seek`
method on :term:`file-like objects <file object>`,
for seeking file data and holes on sparsely allocated files.
:data:`!SEEK_DATA`
Adjust the file offset to the next location containing data,
relative to the seek position.
:data:`!SEEK_HOLE`
Adjust the file offset to the next location containing a hole,
relative to the seek position.
A hole is defined as a sequence of zeros.
.. note::
These operations only make sense for filesystems that support them.
.. availability:: Linux >= 3.1, macOS, Unix
.. versionadded:: 3.3
.. function:: open(path, flags, mode=0o777, *, dir_fd=None)
Open the file *path* and set various flags according to *flags* and possibly
its mode according to *mode*. When computing *mode*, the current umask value
is first masked out. Return the file descriptor for the newly opened file.
The new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
For a description of the flag and mode values, see the C run-time documentation;
flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
the :mod:`os` module. In particular, on Windows adding
:const:`O_BINARY` is needed to open files in binary mode.
This function can support :ref:`paths relative to directory descriptors
<dir_fd>` with the *dir_fd* parameter.
.. audit-event:: open path,mode,flags os.open
.. versionchanged:: 3.4
The new file descriptor is now non-inheritable.
.. note::
This function is intended for low-level I/O. For normal usage, use the
built-in function :func:`open`, which returns a :term:`file object` with
:meth:`~file.read` and :meth:`~file.write` methods (and many more). To
wrap a file descriptor in a file object, use :func:`fdopen`.
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.5
If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
:exc:`InterruptedError` exception (see :pep:`475` for the rationale).
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
The following constants are options for the *flags* parameter to the
:func:`~os.open` function. They can be combined using the bitwise OR operator
``|``. Some of them are not available on all platforms. For descriptions of
their availability and use, consult the :manpage:`open(2)` manual page on Unix
or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
.. data:: O_RDONLY
O_WRONLY
O_RDWR
O_APPEND
O_CREAT
O_EXCL
O_TRUNC
The above constants are available on Unix and Windows.
.. data:: O_DSYNC
O_RSYNC
O_SYNC
O_NDELAY
O_NONBLOCK
O_NOCTTY
O_CLOEXEC
The above constants are only available on Unix.
.. versionchanged:: 3.3
Add :data:`O_CLOEXEC` constant.
.. data:: O_BINARY
O_NOINHERIT
O_SHORT_LIVED
O_TEMPORARY
O_RANDOM
O_SEQUENTIAL
O_TEXT
The above constants are only available on Windows.
.. data:: O_EVTONLY
O_FSYNC
O_SYMLINK
O_NOFOLLOW_ANY
The above constants are only available on macOS.
.. versionchanged:: 3.10
Add :data:`O_EVTONLY`, :data:`O_FSYNC`, :data:`O_SYMLINK`
and :data:`O_NOFOLLOW_ANY` constants.
.. data:: O_ASYNC
O_DIRECT
O_DIRECTORY
O_NOFOLLOW
O_NOATIME
O_PATH
O_TMPFILE
O_SHLOCK
O_EXLOCK
The above constants are extensions and not present if they are not defined by
the C library.
.. versionchanged:: 3.4
Add :data:`O_PATH` on systems that support it.
Add :data:`O_TMPFILE`, only available on Linux Kernel 3.11
or newer.
.. function:: openpty()
.. index:: pair: module; pty
Open a new pseudo-terminal pair. Return a pair of file descriptors
``(master, slave)`` for the pty and the tty, respectively. The new file
descriptors are :ref:`non-inheritable <fd_inheritance>`. For a (slightly) more
portable approach, use the :mod:`pty` module.
.. availability:: Unix, not WASI.
.. versionchanged:: 3.4
The new file descriptors are now non-inheritable.
.. function:: pipe()
Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for
reading and writing, respectively. The new file descriptor is
:ref:`non-inheritable <fd_inheritance>`.
.. availability:: Unix, Windows.
.. versionchanged:: 3.4
The new file descriptors are now non-inheritable.
.. function:: pipe2(flags, /)
Create a pipe with *flags* set atomically.
*flags* can be constructed by ORing together one or more of these values:
:data:`O_NONBLOCK`, :data:`O_CLOEXEC`.
Return a pair of file descriptors ``(r, w)`` usable for reading and writing,
respectively.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. function:: posix_fallocate(fd, offset, len, /)
Ensures that enough disk space is allocated for the file specified by *fd*
starting from *offset* and continuing for *len* bytes.
.. availability:: Unix.
.. versionadded:: 3.3
.. function:: posix_fadvise(fd, offset, len, advice, /)
Announces an intention to access data in a specific pattern thus allowing
the kernel to make optimizations.
The advice applies to the region of the file specified by *fd* starting at
*offset* and continuing for *len* bytes.
*advice* is one of :data:`POSIX_FADV_NORMAL`, :data:`POSIX_FADV_SEQUENTIAL`,
:data:`POSIX_FADV_RANDOM`, :data:`POSIX_FADV_NOREUSE`,
:data:`POSIX_FADV_WILLNEED` or :data:`POSIX_FADV_DONTNEED`.
.. availability:: Unix.
.. versionadded:: 3.3
.. data:: POSIX_FADV_NORMAL
POSIX_FADV_SEQUENTIAL
POSIX_FADV_RANDOM
POSIX_FADV_NOREUSE
POSIX_FADV_WILLNEED
POSIX_FADV_DONTNEED
Flags that can be used in *advice* in :func:`posix_fadvise` that specify
the access pattern that is likely to be used.
.. availability:: Unix.
.. versionadded:: 3.3
.. function:: pread(fd, n, offset, /)
Read at most *n* bytes from file descriptor *fd* at a position of *offset*,
leaving the file offset unchanged.
Return a bytestring containing the bytes read. If the end of the file
referred to by *fd* has been reached, an empty bytes object is returned.
.. availability:: Unix.
.. versionadded:: 3.3
.. function:: posix_openpt(oflag, /)
Open and return a file descriptor for a master pseudo-terminal device.
Calls the C standard library function :c:func:`posix_openpt`. The *oflag*
argument is used to set file status flags and file access modes as
specified in the manual page of :c:func:`posix_openpt` of your system.
The returned file descriptor is :ref:`non-inheritable <fd_inheritance>`.
If the value :data:`O_CLOEXEC` is available on the system, it is added to
*oflag*.
.. availability:: Unix, not WASI.
.. versionadded:: 3.13
.. function:: preadv(fd, buffers, offset, flags=0, /)
Read from a file descriptor *fd* at a position of *offset* into mutable
:term:`bytes-like objects <bytes-like object>` *buffers*, leaving the file
offset unchanged. Transfer data into each buffer until it is full and then
move on to the next buffer in the sequence to hold the rest of the data.
The flags argument contains a bitwise OR of zero or more of the following
flags:
- :data:`RWF_HIPRI`
- :data:`RWF_NOWAIT`
Return the total number of bytes actually read which can be less than the
total capacity of all the objects.
The operating system may set a limit (:func:`sysconf` value
``'SC_IOV_MAX'``) on the number of buffers that can be used.
Combine the functionality of :func:`os.readv` and :func:`os.pread`.
.. availability:: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
Using flags requires Linux >= 4.6.
.. versionadded:: 3.7
.. data:: RWF_NOWAIT
Do not wait for data which is not immediately available. If this flag is
specified, the system call will return instantly if it would have to read
data from the backing storage or wait for a lock.
If some data was successfully read, it will return the number of bytes read.
If no bytes were read, it will return ``-1`` and set errno to
:const:`errno.EAGAIN`.
.. availability:: Linux >= 4.14.
.. versionadded:: 3.7
.. data:: RWF_HIPRI
High priority read/write. Allows block-based filesystems to use polling
of the device, which provides lower latency, but may use additional
resources.
Currently, on Linux, this feature is usable only on a file descriptor opened
using the :data:`O_DIRECT` flag.
.. availability:: Linux >= 4.6.
.. versionadded:: 3.7
.. function:: ptsname(fd, /)
Return the name of the slave pseudo-terminal device associated with the
master pseudo-terminal device to which the file descriptor *fd* refers.
The file descriptor *fd* is not closed upon failure.
Calls the reentrant C standard library function :c:func:`ptsname_r` if
it is available; otherwise, the C standard library function
:c:func:`ptsname`, which is not guaranteed to be thread-safe, is called.
.. availability:: Unix, not WASI.
.. versionadded:: 3.13
.. function:: pwrite(fd, str, offset, /)
Write the bytestring in *str* to file descriptor *fd* at position of
*offset*, leaving the file offset unchanged.
Return the number of bytes actually written.
.. availability:: Unix.
.. versionadded:: 3.3
.. function:: pwritev(fd, buffers, offset, flags=0, /)
Write the *buffers* contents to file descriptor *fd* at an offset *offset*,
leaving the file offset unchanged. *buffers* must be a sequence of
:term:`bytes-like objects <bytes-like object>`. Buffers are processed in
array order. Entire contents of the first buffer is written before
proceeding to the second, and so on.
The flags argument contains a bitwise OR of zero or more of the following
flags:
- :data:`RWF_DSYNC`
- :data:`RWF_SYNC`
- :data:`RWF_APPEND`
Return the total number of bytes actually written.
The operating system may set a limit (:func:`sysconf` value
``'SC_IOV_MAX'``) on the number of buffers that can be used.
Combine the functionality of :func:`os.writev` and :func:`os.pwrite`.
.. availability:: Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
Using flags requires Linux >= 4.6.
.. versionadded:: 3.7
.. data:: RWF_DSYNC
Provide a per-write equivalent of the :data:`O_DSYNC` :func:`os.open` flag.
This flag effect applies only to the data range written by the system call.
.. availability:: Linux >= 4.7.
.. versionadded:: 3.7
.. data:: RWF_SYNC
Provide a per-write equivalent of the :data:`O_SYNC` :func:`os.open` flag.
This flag effect applies only to the data range written by the system call.
.. availability:: Linux >= 4.7.
.. versionadded:: 3.7
.. data:: RWF_APPEND
Provide a per-write equivalent of the :data:`O_APPEND` :func:`os.open`
flag. This flag is meaningful only for :func:`os.pwritev`, and its
effect applies only to the data range written by the system call. The
*offset* argument does not affect the write operation; the data is always
appended to the end of the file. However, if the *offset* argument is
``-1``, the current file *offset* is updated.
.. availability:: Linux >= 4.16.
.. versionadded:: 3.10
.. function:: read(fd, n, /)
Read at most *n* bytes from file descriptor *fd*.
Return a bytestring containing the bytes read. If the end of the file
referred to by *fd* has been reached, an empty bytes object is returned.
.. note::
This function is intended for low-level I/O and must be applied to a file
descriptor as returned by :func:`os.open` or :func:`pipe`. To read a
"file object" returned by the built-in function :func:`open` or by
:func:`popen` or :func:`fdopen`, or :data:`sys.stdin`, use its
:meth:`~file.read` or :meth:`~file.readline` methods.
.. versionchanged:: 3.5
If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
:exc:`InterruptedError` exception (see :pep:`475` for the rationale).
.. function:: sendfile(out_fd, in_fd, offset, count)
sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)
Copy *count* bytes from file descriptor *in_fd* to file descriptor *out_fd*
starting at *offset*.
Return the number of bytes sent. When EOF is reached return ``0``.
The first function notation is supported by all platforms that define
:func:`sendfile`.
On Linux, if *offset* is given as ``None``, the bytes are read from the
current position of *in_fd* and the position of *in_fd* is updated.
The second case may be used on macOS and FreeBSD where *headers* and
*trailers* are arbitrary sequences of buffers that are written before and
after the data from *in_fd* is written. It returns the same as the first case.
On macOS and FreeBSD, a value of ``0`` for *count* specifies to send until
the end of *in_fd* is reached.
All platforms support sockets as *out_fd* file descriptor, and some platforms
allow other types (e.g. regular file, pipe) as well.
Cross-platform applications should not use *headers*, *trailers* and *flags*
arguments.
.. availability:: Unix, not WASI.
.. note::
For a higher-level wrapper of :func:`sendfile`, see
:meth:`socket.socket.sendfile`.
.. versionadded:: 3.3
.. versionchanged:: 3.9
Parameters *out* and *in* was renamed to *out_fd* and *in_fd*.
.. data:: SF_NODISKIO
SF_MNOWAIT
SF_SYNC
Parameters to the :func:`sendfile` function, if the implementation supports
them.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. data:: SF_NOCACHE
Parameter to the :func:`sendfile` function, if the implementation supports
it. The data won't be cached in the virtual memory and will be freed afterwards.
.. availability:: Unix, not WASI.
.. versionadded:: 3.11
.. function:: set_blocking(fd, blocking, /)
Set the blocking mode of the specified file descriptor. Set the
:data:`O_NONBLOCK` flag if blocking is ``False``, clear the flag otherwise.
See also :func:`get_blocking` and :meth:`socket.socket.setblocking`.
.. availability:: Unix, Windows.
The function is limited on WASI, see :ref:`wasm-availability` for more
information.
On Windows, this function is limited to pipes.
.. versionadded:: 3.5
.. versionchanged:: 3.12
Added support for pipes on Windows.
.. function:: splice(src, dst, count, offset_src=None, offset_dst=None)
Transfer *count* bytes from file descriptor *src*, starting from offset
*offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
At least one of the file descriptors must refer to a pipe. If *offset_src*
is ``None``, then *src* is read from the current position; respectively for
*offset_dst*. The offset associated to the file descriptor that refers to a
pipe must be ``None``. The files pointed to by *src* and *dst* must reside in
the same filesystem, otherwise an :exc:`OSError` is raised with
:attr:`~OSError.errno` set to :const:`errno.EXDEV`.
This copy is done without the additional cost of transferring data
from the kernel to user space and then back into the kernel. Additionally,
some filesystems could implement extra optimizations. The copy is done as if
both files are opened as binary.
Upon successful completion, returns the number of bytes spliced to or from
the pipe. A return value of 0 means end of input. If *src* refers to a
pipe, then this means that there was no data to transfer, and it would not
make sense to block because there are no writers connected to the write end
of the pipe.
.. availability:: Linux >= 2.6.17 with glibc >= 2.5
.. versionadded:: 3.10
.. data:: SPLICE_F_MOVE
SPLICE_F_NONBLOCK
SPLICE_F_MORE
.. versionadded:: 3.10
.. function:: readv(fd, buffers, /)
Read from a file descriptor *fd* into a number of mutable :term:`bytes-like
objects <bytes-like object>` *buffers*. Transfer data into each buffer until
it is full and then move on to the next buffer in the sequence to hold the
rest of the data.
Return the total number of bytes actually read which can be less than the
total capacity of all the objects.
The operating system may set a limit (:func:`sysconf` value
``'SC_IOV_MAX'``) on the number of buffers that can be used.
.. availability:: Unix.
.. versionadded:: 3.3
.. function:: tcgetpgrp(fd, /)
Return the process group associated with the terminal given by *fd* (an open
file descriptor as returned by :func:`os.open`).
.. availability:: Unix, not WASI.
.. function:: tcsetpgrp(fd, pg, /)
Set the process group associated with the terminal given by *fd* (an open file
descriptor as returned by :func:`os.open`) to *pg*.
.. availability:: Unix, not WASI.
.. function:: ttyname(fd, /)
Return a string which specifies the terminal device associated with
file descriptor *fd*. If *fd* is not associated with a terminal device, an
exception is raised.
.. availability:: Unix.
.. function:: unlockpt(fd, /)
Unlock the slave pseudo-terminal device associated with the master
pseudo-terminal device to which the file descriptor *fd* refers.
The file descriptor *fd* is not closed upon failure.
Calls the C standard library function :c:func:`unlockpt`.
.. availability:: Unix, not WASI.
.. versionadded:: 3.13
.. function:: write(fd, str, /)
Write the bytestring in *str* to file descriptor *fd*.
Return the number of bytes actually written.
.. note::
This function is intended for low-level I/O and must be applied to a file
descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
object" returned by the built-in function :func:`open` or by :func:`popen` or
:func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
:meth:`~file.write` method.
.. versionchanged:: 3.5
If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
:exc:`InterruptedError` exception (see :pep:`475` for the rationale).
.. function:: writev(fd, buffers, /)
Write the contents of *buffers* to file descriptor *fd*. *buffers* must be
a sequence of :term:`bytes-like objects <bytes-like object>`. Buffers are
processed in array order. Entire contents of the first buffer is written
before proceeding to the second, and so on.
Returns the total number of bytes actually written.
The operating system may set a limit (:func:`sysconf` value
``'SC_IOV_MAX'``) on the number of buffers that can be used.
.. availability:: Unix.
.. versionadded:: 3.3
.. _terminal-size:
Querying the size of a terminal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 3.3
.. function:: get_terminal_size(fd=STDOUT_FILENO, /)
Return the size of the terminal window as ``(columns, lines)``,
tuple of type :class:`terminal_size`.
The optional argument ``fd`` (default ``STDOUT_FILENO``, or standard
output) specifies which file descriptor should be queried.
If the file descriptor is not connected to a terminal, an :exc:`OSError`
is raised.
:func:`shutil.get_terminal_size` is the high-level function which
should normally be used, ``os.get_terminal_size`` is the low-level
implementation.
.. availability:: Unix, Windows.
.. class:: terminal_size
A subclass of tuple, holding ``(columns, lines)`` of the terminal window size.
.. attribute:: columns
Width of the terminal window in characters.
.. attribute:: lines
Height of the terminal window in characters.
.. _fd_inheritance:
Inheritance of File Descriptors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 3.4
A file descriptor has an "inheritable" flag which indicates if the file descriptor
can be inherited by child processes. Since Python 3.4, file descriptors
created by Python are non-inheritable by default.
On UNIX, non-inheritable file descriptors are closed in child processes at the
execution of a new program, other file descriptors are inherited.
On Windows, non-inheritable handles and file descriptors are closed in child
processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout
and stderr), which are always inherited. Using :func:`spawn\* <spawnl>` functions,
all inheritable handles and all inheritable file descriptors are inherited.
Using the :mod:`subprocess` module, all file descriptors except standard
streams are closed, and inheritable handles are only inherited if the
*close_fds* parameter is ``False``.
On WebAssembly platforms, the file descriptor cannot be modified.
.. function:: get_inheritable(fd, /)
Get the "inheritable" flag of the specified file descriptor (a boolean).
.. function:: set_inheritable(fd, inheritable, /)
Set the "inheritable" flag of the specified file descriptor.
.. function:: get_handle_inheritable(handle, /)
Get the "inheritable" flag of the specified handle (a boolean).
.. availability:: Windows.
.. function:: set_handle_inheritable(handle, inheritable, /)
Set the "inheritable" flag of the specified handle.
.. availability:: Windows.
.. _os-file-dir:
Files and Directories
---------------------
On some Unix platforms, many of these functions support one or more of these
features:
.. _path_fd:
* **specifying a file descriptor:**
Normally the *path* argument provided to functions in the :mod:`os` module
must be a string specifying a file path. However, some functions now
alternatively accept an open file descriptor for their *path* argument.
The function will then operate on the file referred to by the descriptor.
(For POSIX systems, Python will call the variant of the function prefixed
with ``f`` (e.g. call ``fchdir`` instead of ``chdir``).)
You can check whether or not *path* can be specified as a file descriptor
for a particular function on your platform using :data:`os.supports_fd`.
If this functionality is unavailable, using it will raise a
:exc:`NotImplementedError`.
If the function also supports *dir_fd* or *follow_symlinks* arguments, it's
an error to specify one of those when supplying *path* as a file descriptor.
.. _dir_fd:
* **paths relative to directory descriptors:** If *dir_fd* is not ``None``, it
should be a file descriptor referring to a directory, and the path to operate
on should be relative; path will then be relative to that directory. If the
path is absolute, *dir_fd* is ignored. (For POSIX systems, Python will call
the variant of the function with an ``at`` suffix and possibly prefixed with
``f`` (e.g. call ``faccessat`` instead of ``access``).
You can check whether or not *dir_fd* is supported for a particular function
on your platform using :data:`os.supports_dir_fd`. If it's unavailable,
using it will raise a :exc:`NotImplementedError`.
.. _follow_symlinks:
* **not following symlinks:** If *follow_symlinks* is
``False``, and the last element of the path to operate on is a symbolic link,
the function will operate on the symbolic link itself rather than the file
pointed to by the link. (For POSIX systems, Python will call the ``l...``
variant of the function.)
You can check whether or not *follow_symlinks* is supported for a particular
function on your platform using :data:`os.supports_follow_symlinks`.
If it's unavailable, using it will raise a :exc:`NotImplementedError`.
.. function:: access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)
Use the real uid/gid to test for access to *path*. Note that most operations
will use the effective uid/gid, therefore this routine can be used in a
suid/sgid environment to test if the invoking user has the specified access to
*path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
:const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
:const:`False` if not. See the Unix man page :manpage:`access(2)` for more
information.
This function can support specifying :ref:`paths relative to directory
descriptors <dir_fd>` and :ref:`not following symlinks <follow_symlinks>`.
If *effective_ids* is ``True``, :func:`access` will perform its access
checks using the effective uid/gid instead of the real uid/gid.
*effective_ids* may not be supported on your platform; you can check whether
or not it is available using :data:`os.supports_effective_ids`. If it is
unavailable, using it will raise a :exc:`NotImplementedError`.
.. note::
Using :func:`access` to check if a user is authorized to e.g. open a file
before actually doing so using :func:`open` creates a security hole,
because the user might exploit the short time interval between checking
and opening the file to manipulate it. It's preferable to use :term:`EAFP`
techniques. For example::
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
return "some default data"
is better written as::
try:
fp = open("myfile")
except PermissionError:
return "some default data"
else:
with fp:
return fp.read()
.. note::
I/O operations may fail even when :func:`access` indicates that they would
succeed, particularly for operations on network filesystems which may have
permissions semantics beyond the usual POSIX permission-bit model.
.. versionchanged:: 3.3
Added the *dir_fd*, *effective_ids*, and *follow_symlinks* parameters.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. data:: F_OK
R_OK
W_OK
X_OK
Values to pass as the *mode* parameter of :func:`access` to test the
existence, readability, writability and executability of *path*,
respectively.
.. function:: chdir(path)
.. index:: single: directory; changing
Change the current working directory to *path*.
This function can support :ref:`specifying a file descriptor <path_fd>`. The
descriptor must refer to an opened directory, not an open file.
This function can raise :exc:`OSError` and subclasses such as
:exc:`FileNotFoundError`, :exc:`PermissionError`, and :exc:`NotADirectoryError`.
.. audit-event:: os.chdir path os.chdir
.. versionchanged:: 3.3
Added support for specifying *path* as a file descriptor
on some platforms.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: chflags(path, flags, *, follow_symlinks=True)
Set the flags of *path* to the numeric *flags*. *flags* may take a combination
(bitwise OR) of the following values (as defined in the :mod:`stat` module):
* :const:`stat.UF_NODUMP`
* :const:`stat.UF_IMMUTABLE`
* :const:`stat.UF_APPEND`
* :const:`stat.UF_OPAQUE`
* :const:`stat.UF_NOUNLINK`
* :const:`stat.UF_COMPRESSED`
* :const:`stat.UF_HIDDEN`
* :const:`stat.SF_ARCHIVED`
* :const:`stat.SF_IMMUTABLE`
* :const:`stat.SF_APPEND`
* :const:`stat.SF_NOUNLINK`
* :const:`stat.SF_SNAPSHOT`
This function can support :ref:`not following symlinks <follow_symlinks>`.
.. audit-event:: os.chflags path,flags os.chflags
.. availability:: Unix, not WASI.
.. versionchanged:: 3.3
Added the *follow_symlinks* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
Change the mode of *path* to the numeric *mode*. *mode* may take one of the
following values (as defined in the :mod:`stat` module) or bitwise ORed
combinations of them:
* :const:`stat.S_ISUID`
* :const:`stat.S_ISGID`
* :const:`stat.S_ENFMT`
* :const:`stat.S_ISVTX`
* :const:`stat.S_IREAD`
* :const:`stat.S_IWRITE`
* :const:`stat.S_IEXEC`
* :const:`stat.S_IRWXU`
* :const:`stat.S_IRUSR`
* :const:`stat.S_IWUSR`
* :const:`stat.S_IXUSR`
* :const:`stat.S_IRWXG`
* :const:`stat.S_IRGRP`
* :const:`stat.S_IWGRP`
* :const:`stat.S_IXGRP`
* :const:`stat.S_IRWXO`
* :const:`stat.S_IROTH`
* :const:`stat.S_IWOTH`
* :const:`stat.S_IXOTH`
This function can support :ref:`specifying a file descriptor <path_fd>`,
:ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
following symlinks <follow_symlinks>`.
.. note::
Although Windows supports :func:`chmod`, you can only set the file's
read-only flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
constants or a corresponding integer value). All other bits are ignored.
The default value of *follow_symlinks* is ``False`` on Windows.
The function is limited on WASI, see :ref:`wasm-availability` for more
information.
.. audit-event:: os.chmod path,mode,dir_fd os.chmod
.. versionchanged:: 3.3
Added support for specifying *path* as an open file descriptor,
and the *dir_fd* and *follow_symlinks* arguments.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.13
Added support for a file descriptor and the *follow_symlinks* argument
on Windows.
.. function:: chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
Change the owner and group id of *path* to the numeric *uid* and *gid*. To
leave one of the ids unchanged, set it to -1.
This function can support :ref:`specifying a file descriptor <path_fd>`,
:ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
following symlinks <follow_symlinks>`.
See :func:`shutil.chown` for a higher-level function that accepts names in
addition to numeric ids.
.. audit-event:: os.chown path,uid,gid,dir_fd os.chown
.. availability:: Unix.
The function is limited on WASI, see :ref:`wasm-availability` for more
information.
.. versionchanged:: 3.3
Added support for specifying *path* as an open file descriptor,
and the *dir_fd* and *follow_symlinks* arguments.
.. versionchanged:: 3.6
Supports a :term:`path-like object`.
.. function:: chroot(path)
Change the root directory of the current process to *path*.
.. availability:: Unix, not WASI, not Android.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: fchdir(fd)
Change the current working directory to the directory represented by the file
descriptor *fd*. The descriptor must refer to an opened directory, not an
open file. As of Python 3.3, this is equivalent to ``os.chdir(fd)``.
.. audit-event:: os.chdir path os.fchdir
.. availability:: Unix.
.. function:: getcwd()
Return a string representing the current working directory.
.. function:: getcwdb()
Return a bytestring representing the current working directory.
.. versionchanged:: 3.8
The function now uses the UTF-8 encoding on Windows, rather than the ANSI
code page: see :pep:`529` for the rationale. The function is no longer
deprecated on Windows.
.. function:: lchflags(path, flags)
Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do
not follow symbolic links. As of Python 3.3, this is equivalent to
``os.chflags(path, flags, follow_symlinks=False)``.
.. audit-event:: os.chflags path,flags os.lchflags
.. availability:: Unix, not WASI.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: lchmod(path, mode)
Change the mode of *path* to the numeric *mode*. If path is a symlink, this
affects the symlink rather than the target. See the docs for :func:`chmod`
for possible values of *mode*. As of Python 3.3, this is equivalent to
``os.chmod(path, mode, follow_symlinks=False)``.
``lchmod()`` is not part of POSIX, but Unix implementations may have it if
changing the mode of symbolic links is supported.
.. audit-event:: os.chmod path,mode,dir_fd os.lchmod
.. availability:: Unix, Windows, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.13
Added support on Windows.
.. function:: lchown(path, uid, gid)
Change the owner and group id of *path* to the numeric *uid* and *gid*. This
function will not follow symbolic links. As of Python 3.3, this is equivalent
to ``os.chown(path, uid, gid, follow_symlinks=False)``.
.. audit-event:: os.chown path,uid,gid,dir_fd os.lchown
.. availability:: Unix.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)
Create a hard link pointing to *src* named *dst*.
This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
supply :ref:`paths relative to directory descriptors <dir_fd>`, and :ref:`not
following symlinks <follow_symlinks>`.
.. audit-event:: os.link src,dst,src_dir_fd,dst_dir_fd os.link
.. availability:: Unix, Windows.
.. versionchanged:: 3.2
Added Windows support.
.. versionchanged:: 3.3
Added the *src_dir_fd*, *dst_dir_fd*, and *follow_symlinks* parameters.
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *src* and *dst*.
.. function:: listdir(path='.')
Return a list containing the names of the entries in the directory given by
*path*. The list is in arbitrary order, and does not include the special
entries ``'.'`` and ``'..'`` even if they are present in the directory.
If a file is removed from or added to the directory during the call of
this function, whether a name for that file be included is unspecified.
*path* may be a :term:`path-like object`. If *path* is of type ``bytes``
(directly or indirectly through the :class:`PathLike` interface),
the filenames returned will also be of type ``bytes``;
in all other circumstances, they will be of type ``str``.
This function can also support :ref:`specifying a file descriptor
<path_fd>`; the file descriptor must refer to a directory.
.. audit-event:: os.listdir path os.listdir
.. note::
To encode ``str`` filenames to ``bytes``, use :func:`~os.fsencode`.
.. seealso::
The :func:`scandir` function returns directory entries along with
file attribute information, giving better performance for many
common use cases.
.. versionchanged:: 3.2
The *path* parameter became optional.
.. versionchanged:: 3.3
Added support for specifying *path* as an open file descriptor.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: listdrives()
Return a list containing the names of drives on a Windows system.
A drive name typically looks like ``'C:\\'``. Not every drive name
will be associated with a volume, and some may be inaccessible for
a variety of reasons, including permissions, network connectivity
or missing media. This function does not test for access.
May raise :exc:`OSError` if an error occurs collecting the drive
names.
.. audit-event:: os.listdrives "" os.listdrives
.. availability:: Windows
.. versionadded:: 3.12
.. function:: listmounts(volume)
Return a list containing the mount points for a volume on a Windows
system.
*volume* must be represented as a GUID path, like those returned by
:func:`os.listvolumes`. Volumes may be mounted in multiple locations
or not at all. In the latter case, the list will be empty. Mount
points that are not associated with a volume will not be returned by
this function.
The mount points return by this function will be absolute paths, and
may be longer than the drive name.
Raises :exc:`OSError` if the volume is not recognized or if an error
occurs collecting the paths.
.. audit-event:: os.listmounts volume os.listmounts
.. availability:: Windows
.. versionadded:: 3.12
.. function:: listvolumes()
Return a list containing the volumes in the system.
Volumes are typically represented as a GUID path that looks like
``\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\``. Files can
usually be accessed through a GUID path, permissions allowing.
However, users are generally not familiar with them, and so the
recommended use of this function is to retrieve mount points
using :func:`os.listmounts`.
May raise :exc:`OSError` if an error occurs collecting the volumes.
.. audit-event:: os.listvolumes "" os.listvolumes
.. availability:: Windows
.. versionadded:: 3.12
.. function:: lstat(path, *, dir_fd=None)
Perform the equivalent of an :c:func:`!lstat` system call on the given path.
Similar to :func:`~os.stat`, but does not follow symbolic links. Return a
:class:`stat_result` object.
On platforms that do not support symbolic links, this is an alias for
:func:`~os.stat`.
As of Python 3.3, this is equivalent to ``os.stat(path, dir_fd=dir_fd,
follow_symlinks=False)``.
This function can also support :ref:`paths relative to directory descriptors
<dir_fd>`.
.. seealso::
The :func:`.stat` function.
.. versionchanged:: 3.2
Added support for Windows 6.0 (Vista) symbolic links.
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.8
On Windows, now opens reparse points that represent another path
(name surrogates), including symbolic links and directory junctions.
Other kinds of reparse points are resolved by the operating system as
for :func:`~os.stat`.
.. function:: mkdir(path, mode=0o777, *, dir_fd=None)
Create a directory named *path* with numeric mode *mode*.
If the directory already exists, :exc:`FileExistsError` is raised. If a parent
directory in the path does not exist, :exc:`FileNotFoundError` is raised.
.. _mkdir_modebits:
On some systems, *mode* is ignored. Where it is used, the current umask
value is first masked out. If bits other than the last 9 (i.e. the last 3
digits of the octal representation of the *mode*) are set, their meaning is
platform-dependent. On some platforms, they are ignored and you should call
:func:`chmod` explicitly to set them.
On Windows, a *mode* of ``0o700`` is specifically handled to apply access
control to the new directory such that only the current user and
administrators have access. Other values of *mode* are ignored.
This function can also support :ref:`paths relative to directory descriptors
<dir_fd>`.
It is also possible to create temporary directories; see the
:mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
.. audit-event:: os.mkdir path,mode,dir_fd os.mkdir
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.13
Windows now handles a *mode* of ``0o700``.
.. function:: makedirs(name, mode=0o777, exist_ok=False)
.. index::
single: directory; creating
single: UNC paths; and os.makedirs()
Recursive directory creation function. Like :func:`mkdir`, but makes all
intermediate-level directories needed to contain the leaf directory.
The *mode* parameter is passed to :func:`mkdir` for creating the leaf
directory; see :ref:`the mkdir() description <mkdir_modebits>` for how it
is interpreted. To set the file permission bits of any newly created parent
directories you can set the umask before invoking :func:`makedirs`. The
file permission bits of existing parent directories are not changed.
If *exist_ok* is ``False`` (the default), a :exc:`FileExistsError` is
raised if the target directory already exists.
.. note::
:func:`makedirs` will become confused if the path elements to create
include :data:`pardir` (eg. ".." on UNIX systems).
This function handles UNC paths correctly.
.. audit-event:: os.mkdir path,mode,dir_fd os.makedirs
.. versionchanged:: 3.2
Added the *exist_ok* parameter.
.. versionchanged:: 3.4.1
Before Python 3.4.1, if *exist_ok* was ``True`` and the directory existed,
:func:`makedirs` would still raise an error if *mode* did not match the
mode of the existing directory. Since this behavior was impossible to
implement safely, it was removed in Python 3.4.1. See :issue:`21082`.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.7
The *mode* argument no longer affects the file permission bits of
newly created intermediate-level directories.
.. function:: mkfifo(path, mode=0o666, *, dir_fd=None)
Create a FIFO (a named pipe) named *path* with numeric mode *mode*.
The current umask value is first masked out from the mode.
This function can also support :ref:`paths relative to directory descriptors
<dir_fd>`.
FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
rendezvous between "client" and "server" type processes: the server opens the
FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
doesn't open the FIFO --- it just creates the rendezvous point.
.. availability:: Unix, not WASI.
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: mknod(path, mode=0o600, device=0, *, dir_fd=None)
Create a filesystem node (file, device special file or named pipe) named
*path*. *mode* specifies both the permissions to use and the type of node
to be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
``stat.S_IFCHR``, ``stat.S_IFBLK``, and ``stat.S_IFIFO`` (those constants are
available in :mod:`stat`). For ``stat.S_IFCHR`` and ``stat.S_IFBLK``,
*device* defines the newly created device special file (probably using
:func:`os.makedev`), otherwise it is ignored.
This function can also support :ref:`paths relative to directory descriptors
<dir_fd>`.
.. availability:: Unix, not WASI.
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: major(device, /)
Extract the device major number from a raw device number (usually the
:attr:`st_dev` or :attr:`st_rdev` field from :c:struct:`stat`).
.. function:: minor(device, /)
Extract the device minor number from a raw device number (usually the
:attr:`st_dev` or :attr:`st_rdev` field from :c:struct:`stat`).
.. function:: makedev(major, minor, /)
Compose a raw device number from the major and minor device numbers.
.. function:: pathconf(path, name)
Return system configuration information relevant to a named file. *name*
specifies the configuration value to retrieve; it may be a string which is the
name of a defined system value; these names are specified in a number of
standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
additional names as well. The names known to the host operating system are
given in the ``pathconf_names`` dictionary. For configuration variables not
included in that mapping, passing an integer for *name* is also accepted.
If *name* is a string and is not known, :exc:`ValueError` is raised. If a
specific value for *name* is not supported by the host system, even if it is
included in ``pathconf_names``, an :exc:`OSError` is raised with
:const:`errno.EINVAL` for the error number.
This function can support :ref:`specifying a file descriptor
<path_fd>`.
.. availability:: Unix.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. data:: pathconf_names
Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
the integer values defined for those names by the host operating system. This
can be used to determine the set of names known to the system.
.. availability:: Unix.
.. function:: readlink(path, *, dir_fd=None)
Return a string representing the path to which the symbolic link points. The
result may be either an absolute or relative pathname; if it is relative, it
may be converted to an absolute pathname using
``os.path.join(os.path.dirname(path), result)``.
If the *path* is a string object (directly or indirectly through a
:class:`PathLike` interface), the result will also be a string object,
and the call may raise a UnicodeDecodeError. If the *path* is a bytes
object (direct or indirectly), the result will be a bytes object.
This function can also support :ref:`paths relative to directory descriptors
<dir_fd>`.
When trying to resolve a path that may contain links, use
:func:`~os.path.realpath` to properly handle recursion and platform
differences.
.. availability:: Unix, Windows.
.. versionchanged:: 3.2
Added support for Windows 6.0 (Vista) symbolic links.
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object` on Unix.
.. versionchanged:: 3.8
Accepts a :term:`path-like object` and a bytes object on Windows.
Added support for directory junctions, and changed to return the
substitution path (which typically includes ``\\?\`` prefix) rather
than the optional "print name" field that was previously returned.
.. function:: remove(path, *, dir_fd=None)
Remove (delete) the file *path*. If *path* is a directory, an
:exc:`OSError` is raised. Use :func:`rmdir` to remove directories.
If the file does not exist, a :exc:`FileNotFoundError` is raised.
This function can support :ref:`paths relative to directory descriptors
<dir_fd>`.
On Windows, attempting to remove a file that is in use causes an exception to
be raised; on Unix, the directory entry is removed but the storage allocated
to the file is not made available until the original file is no longer in use.
This function is semantically identical to :func:`unlink`.
.. audit-event:: os.remove path,dir_fd os.remove
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: removedirs(name)
.. index:: single: directory; deleting
Remove directories recursively. Works like :func:`rmdir` except that, if the
leaf directory is successfully removed, :func:`removedirs` tries to
successively remove every parent directory mentioned in *path* until an error
is raised (which is ignored, because it generally means that a parent directory
is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
they are empty. Raises :exc:`OSError` if the leaf directory could not be
successfully removed.
.. audit-event:: os.remove path,dir_fd os.removedirs
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory *src* to *dst*. If *dst* exists, the operation
will fail with an :exc:`OSError` subclass in a number of cases:
On Windows, if *dst* exists a :exc:`FileExistsError` is always raised.
The operation may fail if *src* and *dst* are on different filesystems. Use
:func:`shutil.move` to support moves to a different filesystem.
On Unix, if *src* is a file and *dst* is a directory or vice-versa, an
:exc:`IsADirectoryError` or a :exc:`NotADirectoryError` will be raised
respectively. If both are directories and *dst* is empty, *dst* will be
silently replaced. If *dst* is a non-empty directory, an :exc:`OSError`
is raised. If both are files, *dst* will be replaced silently if the user
has permission. The operation may fail on some Unix flavors if *src* and
*dst* are on different filesystems. If successful, the renaming will be an
atomic operation (this is a POSIX requirement).
This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
supply :ref:`paths relative to directory descriptors <dir_fd>`.
If you want cross-platform overwriting of the destination, use :func:`replace`.
.. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.rename
.. versionchanged:: 3.3
Added the *src_dir_fd* and *dst_dir_fd* parameters.
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *src* and *dst*.
.. function:: renames(old, new)
Recursive directory or file renaming function. Works like :func:`rename`, except
creation of any intermediate directories needed to make the new pathname good is
attempted first. After the rename, directories corresponding to rightmost path
segments of the old name will be pruned away using :func:`removedirs`.
.. note::
This function can fail with the new directory structure made if you lack
permissions needed to remove the leaf directory or file.
.. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.renames
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *old* and *new*.
.. function:: replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory *src* to *dst*. If *dst* is a non-empty directory,
:exc:`OSError` will be raised. If *dst* exists and is a file, it will
be replaced silently if the user has permission. The operation may fail
if *src* and *dst* are on different filesystems. If successful,
the renaming will be an atomic operation (this is a POSIX requirement).
This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to
supply :ref:`paths relative to directory descriptors <dir_fd>`.
.. audit-event:: os.rename src,dst,src_dir_fd,dst_dir_fd os.replace
.. versionadded:: 3.3
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *src* and *dst*.
.. function:: rmdir(path, *, dir_fd=None)
Remove (delete) the directory *path*. If the directory does not exist or is
not empty, a :exc:`FileNotFoundError` or an :exc:`OSError` is raised
respectively. In order to remove whole directory trees,
:func:`shutil.rmtree` can be used.
This function can support :ref:`paths relative to directory descriptors
<dir_fd>`.
.. audit-event:: os.rmdir path,dir_fd os.rmdir
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: scandir(path='.')
Return an iterator of :class:`os.DirEntry` objects corresponding to the
entries in the directory given by *path*. The entries are yielded in
arbitrary order, and the special entries ``'.'`` and ``'..'`` are not
included. If a file is removed from or added to the directory after
creating the iterator, whether an entry for that file be included is
unspecified.
Using :func:`scandir` instead of :func:`listdir` can significantly
increase the performance of code that also needs file type or file
attribute information, because :class:`os.DirEntry` objects expose this
information if the operating system provides it when scanning a directory.
All :class:`os.DirEntry` methods may perform a system call, but
:func:`~os.DirEntry.is_dir` and :func:`~os.DirEntry.is_file` usually only
require a system call for symbolic links; :func:`os.DirEntry.stat`
always requires a system call on Unix but only requires one for
symbolic links on Windows.
*path* may be a :term:`path-like object`. If *path* is of type ``bytes``
(directly or indirectly through the :class:`PathLike` interface),
the type of the :attr:`~os.DirEntry.name` and :attr:`~os.DirEntry.path`
attributes of each :class:`os.DirEntry` will be ``bytes``; in all other
circumstances, they will be of type ``str``.
This function can also support :ref:`specifying a file descriptor
<path_fd>`; the file descriptor must refer to a directory.
.. audit-event:: os.scandir path os.scandir
The :func:`scandir` iterator supports the :term:`context manager` protocol
and has the following method:
.. method:: scandir.close()
Close the iterator and free acquired resources.
This is called automatically when the iterator is exhausted or garbage
collected, or when an error happens during iterating. However it
is advisable to call it explicitly or use the :keyword:`with`
statement.
.. versionadded:: 3.6
The following example shows a simple use of :func:`scandir` to display all
the files (excluding directories) in the given *path* that don't start with
``'.'``. The ``entry.is_file()`` call will generally not make an additional
system call::
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)
.. note::
On Unix-based systems, :func:`scandir` uses the system's
`opendir() <https://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html>`_
and
`readdir() <https://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html>`_
functions. On Windows, it uses the Win32
`FindFirstFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx>`_
and
`FindNextFileW <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx>`_
functions.
.. versionadded:: 3.5
.. versionchanged:: 3.6
Added support for the :term:`context manager` protocol and the
:func:`~scandir.close` method. If a :func:`scandir` iterator is neither
exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted
in its destructor.
The function accepts a :term:`path-like object`.
.. versionchanged:: 3.7
Added support for :ref:`file descriptors <path_fd>` on Unix.
.. class:: DirEntry
Object yielded by :func:`scandir` to expose the file path and other file
attributes of a directory entry.
:func:`scandir` will provide as much of this information as possible without
making additional system calls. When a ``stat()`` or ``lstat()`` system call
is made, the ``os.DirEntry`` object will cache the result.
``os.DirEntry`` instances are not intended to be stored in long-lived data
structures; if you know the file metadata has changed or if a long time has
elapsed since calling :func:`scandir`, call ``os.stat(entry.path)`` to fetch
up-to-date information.
Because the ``os.DirEntry`` methods can make operating system calls, they may
also raise :exc:`OSError`. If you need very fine-grained
control over errors, you can catch :exc:`OSError` when calling one of the
``os.DirEntry`` methods and handle as appropriate.
To be directly usable as a :term:`path-like object`, ``os.DirEntry``
implements the :class:`PathLike` interface.
Attributes and methods on a ``os.DirEntry`` instance are as follows:
.. attribute:: name
The entry's base filename, relative to the :func:`scandir` *path*
argument.
The :attr:`name` attribute will be ``bytes`` if the :func:`scandir`
*path* argument is of type ``bytes`` and ``str`` otherwise. Use
:func:`~os.fsdecode` to decode byte filenames.
.. attribute:: path
The entry's full path name: equivalent to ``os.path.join(scandir_path,
entry.name)`` where *scandir_path* is the :func:`scandir` *path*
argument. The path is only absolute if the :func:`scandir` *path*
argument was absolute. If the :func:`scandir` *path*
argument was a :ref:`file descriptor <path_fd>`, the :attr:`path`
attribute is the same as the :attr:`name` attribute.
The :attr:`path` attribute will be ``bytes`` if the :func:`scandir`
*path* argument is of type ``bytes`` and ``str`` otherwise. Use
:func:`~os.fsdecode` to decode byte filenames.
.. method:: inode()
Return the inode number of the entry.
The result is cached on the ``os.DirEntry`` object. Use
``os.stat(entry.path, follow_symlinks=False).st_ino`` to fetch up-to-date
information.
On the first, uncached call, a system call is required on Windows but
not on Unix.
.. method:: is_dir(*, follow_symlinks=True)
Return ``True`` if this entry is a directory or a symbolic link pointing
to a directory; return ``False`` if the entry is or points to any other
kind of file, or if it doesn't exist anymore.
If *follow_symlinks* is ``False``, return ``True`` only if this entry
is a directory (without following symlinks); return ``False`` if the
entry is any other kind of file or if it doesn't exist anymore.
The result is cached on the ``os.DirEntry`` object, with a separate cache
for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` along
with :func:`stat.S_ISDIR` to fetch up-to-date information.
On the first, uncached call, no system call is required in most cases.
Specifically, for non-symlinks, neither Windows or Unix require a system
call, except on certain Unix file systems, such as network file systems,
that return ``dirent.d_type == DT_UNKNOWN``. If the entry is a symlink,
a system call will be required to follow the symlink unless
*follow_symlinks* is ``False``.
This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
but :exc:`FileNotFoundError` is caught and not raised.
.. method:: is_file(*, follow_symlinks=True)
Return ``True`` if this entry is a file or a symbolic link pointing to a
file; return ``False`` if the entry is or points to a directory or other
non-file entry, or if it doesn't exist anymore.
If *follow_symlinks* is ``False``, return ``True`` only if this entry
is a file (without following symlinks); return ``False`` if the entry is
a directory or other non-file entry, or if it doesn't exist anymore.
The result is cached on the ``os.DirEntry`` object. Caching, system calls
made, and exceptions raised are as per :func:`~os.DirEntry.is_dir`.
.. method:: is_symlink()
Return ``True`` if this entry is a symbolic link (even if broken);
return ``False`` if the entry points to a directory or any kind of file,
or if it doesn't exist anymore.
The result is cached on the ``os.DirEntry`` object. Call
:func:`os.path.islink` to fetch up-to-date information.
On the first, uncached call, no system call is required in most cases.
Specifically, neither Windows or Unix require a system call, except on
certain Unix file systems, such as network file systems, that return
``dirent.d_type == DT_UNKNOWN``.
This method can raise :exc:`OSError`, such as :exc:`PermissionError`,
but :exc:`FileNotFoundError` is caught and not raised.
.. method:: is_junction()
Return ``True`` if this entry is a junction (even if broken);
return ``False`` if the entry points to a regular directory, any kind
of file, a symlink, or if it doesn't exist anymore.
The result is cached on the ``os.DirEntry`` object. Call
:func:`os.path.isjunction` to fetch up-to-date information.
.. versionadded:: 3.12
.. method:: stat(*, follow_symlinks=True)
Return a :class:`stat_result` object for this entry. This method
follows symbolic links by default; to stat a symbolic link add the
``follow_symlinks=False`` argument.
On Unix, this method always requires a system call. On Windows, it
only requires a system call if *follow_symlinks* is ``True`` and the
entry is a reparse point (for example, a symbolic link or directory
junction).
On Windows, the ``st_ino``, ``st_dev`` and ``st_nlink`` attributes of the
:class:`stat_result` are always set to zero. Call :func:`os.stat` to
get these attributes.
The result is cached on the ``os.DirEntry`` object, with a separate cache
for *follow_symlinks* ``True`` and ``False``. Call :func:`os.stat` to
fetch up-to-date information.
Note that there is a nice correspondence between several attributes
and methods of ``os.DirEntry`` and of :class:`pathlib.Path`. In
particular, the ``name`` attribute has the same
meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()``,
``is_junction()``, and ``stat()`` methods.
.. versionadded:: 3.5
.. versionchanged:: 3.6
Added support for the :class:`~os.PathLike` interface. Added support
for :class:`bytes` paths on Windows.
.. versionchanged:: 3.12
The ``st_ctime`` attribute of a stat result is deprecated on Windows.
The file creation time is properly available as ``st_birthtime``, and
in the future ``st_ctime`` may be changed to return zero or the
metadata change time, if available.
.. function:: stat(path, *, dir_fd=None, follow_symlinks=True)
Get the status of a file or a file descriptor. Perform the equivalent of a
:c:func:`stat` system call on the given path. *path* may be specified as
either a string or bytes -- directly or indirectly through the :class:`PathLike`
interface -- or as an open file descriptor. Return a :class:`stat_result`
object.
This function normally follows symlinks; to stat a symlink add the argument
``follow_symlinks=False``, or use :func:`lstat`.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
On Windows, passing ``follow_symlinks=False`` will disable following all
name-surrogate reparse points, which includes symlinks and directory
junctions. Other types of reparse points that do not resemble links or that
the operating system is unable to follow will be opened directly. When
following a chain of multiple links, this may result in the original link
being returned instead of the non-link that prevented full traversal. To
obtain stat results for the final path in this case, use the
:func:`os.path.realpath` function to resolve the path name as far as
possible and call :func:`lstat` on the result. This does not apply to
dangling symlinks or junction points, which will raise the usual exceptions.
.. index:: pair: module; stat
Example::
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
.. seealso::
:func:`fstat` and :func:`lstat` functions.
.. versionchanged:: 3.3
Added the *dir_fd* and *follow_symlinks* parameters,
specifying a file descriptor instead of a path.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.8
On Windows, all reparse points that can be resolved by the operating
system are now followed, and passing ``follow_symlinks=False``
disables following all name surrogate reparse points. If the operating
system reaches a reparse point that it is not able to follow, *stat* now
returns the information for the original path as if
``follow_symlinks=False`` had been specified instead of raising an error.
.. class:: stat_result
Object whose attributes correspond roughly to the members of the
:c:struct:`stat` structure. It is used for the result of :func:`os.stat`,
:func:`os.fstat` and :func:`os.lstat`.
Attributes:
.. attribute:: st_mode
File mode: file type and file mode bits (permissions).
.. attribute:: st_ino
Platform dependent, but if non-zero, uniquely identifies the
file for a given value of ``st_dev``. Typically:
* the inode number on Unix,
* the `file index
<https://msdn.microsoft.com/en-us/library/aa363788>`_ on
Windows
.. attribute:: st_dev
Identifier of the device on which this file resides.
.. attribute:: st_nlink
Number of hard links.
.. attribute:: st_uid
User identifier of the file owner.
.. attribute:: st_gid
Group identifier of the file owner.
.. attribute:: st_size
Size of the file in bytes, if it is a regular file or a symbolic link.
The size of a symbolic link is the length of the pathname it contains,
without a terminating null byte.
Timestamps:
.. attribute:: st_atime
Time of most recent access expressed in seconds.
.. attribute:: st_mtime
Time of most recent content modification expressed in seconds.
.. attribute:: st_ctime
Time of most recent metadata change expressed in seconds.
.. versionchanged:: 3.12
``st_ctime`` is deprecated on Windows. Use ``st_birthtime`` for
the file creation time. In the future, ``st_ctime`` will contain
the time of the most recent metadata change, as for other platforms.
.. attribute:: st_atime_ns
Time of most recent access expressed in nanoseconds as an integer.
.. versionadded:: 3.3
.. attribute:: st_mtime_ns
Time of most recent content modification expressed in nanoseconds as an
integer.
.. versionadded:: 3.3
.. attribute:: st_ctime_ns
Time of most recent metadata change expressed in nanoseconds as an
integer.
.. versionadded:: 3.3
.. versionchanged:: 3.12
``st_ctime_ns`` is deprecated on Windows. Use ``st_birthtime_ns``
for the file creation time. In the future, ``st_ctime`` will contain
the time of the most recent metadata change, as for other platforms.
.. attribute:: st_birthtime
Time of file creation expressed in seconds. This attribute is not
always available, and may raise :exc:`AttributeError`.
.. versionchanged:: 3.12
``st_birthtime`` is now available on Windows.
.. attribute:: st_birthtime_ns
Time of file creation expressed in nanoseconds as an integer.
This attribute is not always available, and may raise
:exc:`AttributeError`.
.. versionadded:: 3.12
.. note::
The exact meaning and resolution of the :attr:`st_atime`,
:attr:`st_mtime`, :attr:`st_ctime` and :attr:`st_birthtime` attributes
depend on the operating system and the file system. For example, on
Windows systems using the FAT32 file systems, :attr:`st_mtime` has
2-second resolution, and :attr:`st_atime` has only 1-day resolution.
See your operating system documentation for details.
Similarly, although :attr:`st_atime_ns`, :attr:`st_mtime_ns`,
:attr:`st_ctime_ns` and :attr:`st_birthtime_ns` are always expressed in
nanoseconds, many systems do not provide nanosecond precision. On
systems that do provide nanosecond precision, the floating-point object
used to store :attr:`st_atime`, :attr:`st_mtime`, :attr:`st_ctime` and
:attr:`st_birthtime` cannot preserve all of it, and as such will be
slightly inexact. If you need the exact timestamps you should always use
:attr:`st_atime_ns`, :attr:`st_mtime_ns`, :attr:`st_ctime_ns` and
:attr:`st_birthtime_ns`.
On some Unix systems (such as Linux), the following attributes may also be
available:
.. attribute:: st_blocks
Number of 512-byte blocks allocated for file.
This may be smaller than :attr:`st_size`/512 when the file has holes.
.. attribute:: st_blksize
"Preferred" blocksize for efficient file system I/O. Writing to a file in
smaller chunks may cause an inefficient read-modify-rewrite.
.. attribute:: st_rdev
Type of device if an inode device.
.. attribute:: st_flags
User defined flags for file.
On other Unix systems (such as FreeBSD), the following attributes may be
available (but may be only filled out if root tries to use them):
.. attribute:: st_gen
File generation number.
On Solaris and derivatives, the following attributes may also be
available:
.. attribute:: st_fstype
String that uniquely identifies the type of the filesystem that
contains the file.
On macOS systems, the following attributes may also be available:
.. attribute:: st_rsize
Real size of the file.
.. attribute:: st_creator
Creator of the file.
.. attribute:: st_type
File type.
On Windows systems, the following attributes are also available:
.. attribute:: st_file_attributes
Windows file attributes: ``dwFileAttributes`` member of the
``BY_HANDLE_FILE_INFORMATION`` structure returned by
:c:func:`!GetFileInformationByHandle`.
See the :const:`!FILE_ATTRIBUTE_* <stat.FILE_ATTRIBUTE_ARCHIVE>`
constants in the :mod:`stat` module.
.. versionadded:: 3.5
.. attribute:: st_reparse_tag
When :attr:`st_file_attributes` has the :const:`~stat.FILE_ATTRIBUTE_REPARSE_POINT`
set, this field contains the tag identifying the type of reparse point.
See the :const:`IO_REPARSE_TAG_* <stat.IO_REPARSE_TAG_SYMLINK>`
constants in the :mod:`stat` module.
The standard module :mod:`stat` defines functions and constants that are
useful for extracting information from a :c:struct:`stat` structure. (On
Windows, some items are filled with dummy values.)
For backward compatibility, a :class:`stat_result` instance is also
accessible as a tuple of at least 10 integers giving the most important (and
portable) members of the :c:struct:`stat` structure, in the order
:attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`,
:attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`,
:attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by
some implementations. For compatibility with older Python versions,
accessing :class:`stat_result` as a tuple always returns integers.
.. versionchanged:: 3.5
Windows now returns the file index as :attr:`st_ino` when
available.
.. versionchanged:: 3.7
Added the :attr:`st_fstype` member to Solaris/derivatives.
.. versionchanged:: 3.8
Added the :attr:`st_reparse_tag` member on Windows.
.. versionchanged:: 3.8
On Windows, the :attr:`st_mode` member now identifies special
files as :const:`S_IFCHR`, :const:`S_IFIFO` or :const:`S_IFBLK`
as appropriate.
.. versionchanged:: 3.12
On Windows, :attr:`st_ctime` is deprecated. Eventually, it will
contain the last metadata change time, for consistency with other
platforms, but for now still contains creation time.
Use :attr:`st_birthtime` for the creation time.
On Windows, :attr:`st_ino` may now be up to 128 bits, depending
on the file system. Previously it would not be above 64 bits, and
larger file identifiers would be arbitrarily packed.
On Windows, :attr:`st_rdev` no longer returns a value. Previously
it would contain the same as :attr:`st_dev`, which was incorrect.
Added the :attr:`st_birthtime` member on Windows.
.. function:: statvfs(path)
Perform a :c:func:`!statvfs` system call on the given path. The return value is
an object whose attributes describe the filesystem on the given path, and
correspond to the members of the :c:struct:`statvfs` structure, namely:
:attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
:attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
:attr:`f_flag`, :attr:`f_namemax`, :attr:`f_fsid`.
Two module-level constants are defined for the :attr:`f_flag` attribute's
bit-flags: if :const:`ST_RDONLY` is set, the filesystem is mounted
read-only, and if :const:`ST_NOSUID` is set, the semantics of
setuid/setgid bits are disabled or not supported.
Additional module-level constants are defined for GNU/glibc based systems.
These are :const:`ST_NODEV` (disallow access to device special files),
:const:`ST_NOEXEC` (disallow program execution), :const:`ST_SYNCHRONOUS`
(writes are synced at once), :const:`ST_MANDLOCK` (allow mandatory locks on an FS),
:const:`ST_WRITE` (write on file/directory/symlink), :const:`ST_APPEND`
(append-only file), :const:`ST_IMMUTABLE` (immutable file), :const:`ST_NOATIME`
(do not update access times), :const:`ST_NODIRATIME` (do not update directory access
times), :const:`ST_RELATIME` (update atime relative to mtime/ctime).
This function can support :ref:`specifying a file descriptor <path_fd>`.
.. availability:: Unix.
.. versionchanged:: 3.2
The :const:`ST_RDONLY` and :const:`ST_NOSUID` constants were added.
.. versionchanged:: 3.3
Added support for specifying *path* as an open file descriptor.
.. versionchanged:: 3.4
The :const:`ST_NODEV`, :const:`ST_NOEXEC`, :const:`ST_SYNCHRONOUS`,
:const:`ST_MANDLOCK`, :const:`ST_WRITE`, :const:`ST_APPEND`,
:const:`ST_IMMUTABLE`, :const:`ST_NOATIME`, :const:`ST_NODIRATIME`,
and :const:`ST_RELATIME` constants were added.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.7
Added the :attr:`f_fsid` attribute.
.. data:: supports_dir_fd
A :class:`set` object indicating which functions in the :mod:`os`
module accept an open file descriptor for their *dir_fd* parameter.
Different platforms provide different features, and the underlying
functionality Python uses to implement the *dir_fd* parameter is not
available on all platforms Python supports. For consistency's sake,
functions that may support *dir_fd* always allow specifying the
parameter, but will throw an exception if the functionality is used
when it's not locally available. (Specifying ``None`` for *dir_fd*
is always supported on all platforms.)
To check whether a particular function accepts an open file descriptor
for its *dir_fd* parameter, use the ``in`` operator on ``supports_dir_fd``.
As an example, this expression evaluates to ``True`` if :func:`os.stat`
accepts open file descriptors for *dir_fd* on the local platform::
os.stat in os.supports_dir_fd
Currently *dir_fd* parameters only work on Unix platforms;
none of them work on Windows.
.. versionadded:: 3.3
.. data:: supports_effective_ids
A :class:`set` object indicating whether :func:`os.access` permits
specifying ``True`` for its *effective_ids* parameter on the local platform.
(Specifying ``False`` for *effective_ids* is always supported on all
platforms.) If the local platform supports it, the collection will contain
:func:`os.access`; otherwise it will be empty.
This expression evaluates to ``True`` if :func:`os.access` supports
``effective_ids=True`` on the local platform::
os.access in os.supports_effective_ids
Currently *effective_ids* is only supported on Unix platforms;
it does not work on Windows.
.. versionadded:: 3.3
.. data:: supports_fd
A :class:`set` object indicating which functions in the
:mod:`os` module permit specifying their *path* parameter as an open file
descriptor on the local platform. Different platforms provide different
features, and the underlying functionality Python uses to accept open file
descriptors as *path* arguments is not available on all platforms Python
supports.
To determine whether a particular function permits specifying an open file
descriptor for its *path* parameter, use the ``in`` operator on
``supports_fd``. As an example, this expression evaluates to ``True`` if
:func:`os.chdir` accepts open file descriptors for *path* on your local
platform::
os.chdir in os.supports_fd
.. versionadded:: 3.3
.. data:: supports_follow_symlinks
A :class:`set` object indicating which functions in the :mod:`os` module
accept ``False`` for their *follow_symlinks* parameter on the local platform.
Different platforms provide different features, and the underlying
functionality Python uses to implement *follow_symlinks* is not available
on all platforms Python supports. For consistency's sake, functions that
may support *follow_symlinks* always allow specifying the parameter, but
will throw an exception if the functionality is used when it's not locally
available. (Specifying ``True`` for *follow_symlinks* is always supported
on all platforms.)
To check whether a particular function accepts ``False`` for its
*follow_symlinks* parameter, use the ``in`` operator on
``supports_follow_symlinks``. As an example, this expression evaluates
to ``True`` if you may specify ``follow_symlinks=False`` when calling
:func:`os.stat` on the local platform::
os.stat in os.supports_follow_symlinks
.. versionadded:: 3.3
.. function:: symlink(src, dst, target_is_directory=False, *, dir_fd=None)
Create a symbolic link pointing to *src* named *dst*.
On Windows, a symlink represents either a file or a directory, and does not
morph to the target dynamically. If the target is present, the type of the
symlink will be created to match. Otherwise, the symlink will be created
as a directory if *target_is_directory* is ``True`` or a file symlink (the
default) otherwise. On non-Windows platforms, *target_is_directory* is ignored.
This function can support :ref:`paths relative to directory descriptors
<dir_fd>`.
.. note::
On newer versions of Windows 10, unprivileged accounts can create symlinks
if Developer Mode is enabled. When Developer Mode is not available/enabled,
the *SeCreateSymbolicLinkPrivilege* privilege is required, or the process
must be run as an administrator.
:exc:`OSError` is raised when the function is called by an unprivileged
user.
.. audit-event:: os.symlink src,dst,dir_fd os.symlink
.. availability:: Unix, Windows.
The function is limited on WASI, see :ref:`wasm-availability` for more
information.
.. versionchanged:: 3.2
Added support for Windows 6.0 (Vista) symbolic links.
.. versionchanged:: 3.3
Added the *dir_fd* parameter, and now allow *target_is_directory*
on non-Windows platforms.
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *src* and *dst*.
.. versionchanged:: 3.8
Added support for unelevated symlinks on Windows with Developer Mode.
.. function:: sync()
Force write of everything to disk.
.. availability:: Unix.
.. versionadded:: 3.3
.. function:: truncate(path, length)
Truncate the file corresponding to *path*, so that it is at most
*length* bytes in size.
This function can support :ref:`specifying a file descriptor <path_fd>`.
.. audit-event:: os.truncate path,length os.truncate
.. availability:: Unix, Windows.
.. versionadded:: 3.3
.. versionchanged:: 3.5
Added support for Windows
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: unlink(path, *, dir_fd=None)
Remove (delete) the file *path*. This function is semantically
identical to :func:`remove`; the ``unlink`` name is its
traditional Unix name. Please see the documentation for
:func:`remove` for further information.
.. audit-event:: os.remove path,dir_fd os.unlink
.. versionchanged:: 3.3
Added the *dir_fd* parameter.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)
Set the access and modified times of the file specified by *path*.
:func:`utime` takes two optional parameters, *times* and *ns*.
These specify the times set on *path* and are used as follows:
- If *ns* is specified,
it must be a 2-tuple of the form ``(atime_ns, mtime_ns)``
where each member is an int expressing nanoseconds.
- If *times* is not ``None``,
it must be a 2-tuple of the form ``(atime, mtime)``
where each member is an int or float expressing seconds.
- If *times* is ``None`` and *ns* is unspecified,
this is equivalent to specifying ``ns=(atime_ns, mtime_ns)``
where both times are the current time.
It is an error to specify tuples for both *times* and *ns*.
Note that the exact times you set here may not be returned by a subsequent
:func:`~os.stat` call, depending on the resolution with which your operating
system records access and modification times; see :func:`~os.stat`. The best
way to preserve exact times is to use the *st_atime_ns* and *st_mtime_ns*
fields from the :func:`os.stat` result object with the *ns* parameter to
:func:`utime`.
This function can support :ref:`specifying a file descriptor <path_fd>`,
:ref:`paths relative to directory descriptors <dir_fd>` and :ref:`not
following symlinks <follow_symlinks>`.
.. audit-event:: os.utime path,times,ns,dir_fd os.utime
.. versionchanged:: 3.3
Added support for specifying *path* as an open file descriptor,
and the *dir_fd*, *follow_symlinks*, and *ns* parameters.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
.. index::
single: directory; walking
single: directory; traversal
Generate the file names in a directory tree by walking the tree
either top-down or bottom-up. For each directory in the tree rooted at directory
*top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
filenames)``.
*dirpath* is a string, the path to the directory. *dirnames* is a list of the
names of the subdirectories in *dirpath* (including symlinks to directories,
and excluding ``'.'`` and ``'..'``).
*filenames* is a list of the names of the non-directory files in *dirpath*.
Note that the names in the lists contain no path components. To get a full path
(which begins with *top*) to a file or directory in *dirpath*, do
``os.path.join(dirpath, name)``. Whether or not the lists are sorted
depends on the file system. If a file is removed from or added to the
*dirpath* directory during generating the lists, whether a name for that
file be included is unspecified.
If optional argument *topdown* is ``True`` or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top-down). If *topdown* is ``False``, the triple
for a directory is generated after the triples for all of its subdirectories
(directories are generated bottom-up). No matter the value of *topdown*, the
list of subdirectories is retrieved before the tuples for the directory and
its subdirectories are generated.
When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
(perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
recurse into the subdirectories whose names remain in *dirnames*; this can be
used to prune the search, impose a specific order of visiting, or even to inform
:func:`walk` about directories the caller creates or renames before it resumes
:func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` has
no effect on the behavior of the walk, because in bottom-up mode the directories
in *dirnames* are generated before *dirpath* itself is generated.
By default, errors from the :func:`scandir` call are ignored. If optional
argument *onerror* is specified, it should be a function; it will be called with
one argument, an :exc:`OSError` instance. It can report the error to continue
with the walk, or raise the exception to abort the walk. Note that the filename
is available as the ``filename`` attribute of the exception object.
By default, :func:`walk` will not walk down into symbolic links that resolve to
directories. Set *followlinks* to ``True`` to visit directories pointed to by
symlinks, on systems that support them.
.. note::
Be aware that setting *followlinks* to ``True`` can lead to infinite
recursion if a link points to a parent directory of itself. :func:`walk`
does not keep track of the directories it visited already.
.. note::
If you pass a relative pathname, don't change the current working directory
between resumptions of :func:`walk`. :func:`walk` never changes the current
directory, and assumes that its caller doesn't either.
This example displays the number of bytes taken by non-directory files in each
directory under the starting directory, except that it doesn't look under any
``__pycache__`` subdirectory::
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/xml'):
print(root, "consumes", end=" ")
print(sum(getsize(join(root, name)) for name in files), end=" ")
print("bytes in", len(files), "non-directory files")
if '__pycache__' in dirs:
dirs.remove('__pycache__') # don't visit __pycache__ directories
In the next example (simple implementation of :func:`shutil.rmtree`),
walking the tree bottom-up is essential, :func:`rmdir` doesn't allow
deleting a directory before the directory is empty::
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(top)
.. audit-event:: os.walk top,topdown,onerror,followlinks os.walk
.. versionchanged:: 3.5
This function now calls :func:`os.scandir` instead of :func:`os.listdir`,
making it faster by reducing the number of calls to :func:`os.stat`.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
.. index::
single: directory; walking
single: directory; traversal
This behaves exactly like :func:`walk`, except that it yields a 4-tuple
``(dirpath, dirnames, filenames, dirfd)``, and it supports ``dir_fd``.
*dirpath*, *dirnames* and *filenames* are identical to :func:`walk` output,
and *dirfd* is a file descriptor referring to the directory *dirpath*.
This function always supports :ref:`paths relative to directory descriptors
<dir_fd>` and :ref:`not following symlinks <follow_symlinks>`. Note however
that, unlike other functions, the :func:`fwalk` default value for
*follow_symlinks* is ``False``.
.. note::
Since :func:`fwalk` yields file descriptors, those are only valid until
the next iteration step, so you should duplicate them (e.g. with
:func:`dup`) if you want to keep them longer.
This example displays the number of bytes taken by non-directory files in each
directory under the starting directory, except that it doesn't look under any
``__pycache__`` subdirectory::
import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/xml'):
print(root, "consumes", end="")
print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
end="")
print("bytes in", len(files), "non-directory files")
if '__pycache__' in dirs:
dirs.remove('__pycache__') # don't visit __pycache__ directories
In the next example, walking the tree bottom-up is essential:
:func:`rmdir` doesn't allow deleting a directory before the directory is
empty::
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
for name in files:
os.unlink(name, dir_fd=rootfd)
for name in dirs:
os.rmdir(name, dir_fd=rootfd)
.. audit-event:: os.fwalk top,topdown,onerror,follow_symlinks,dir_fd os.fwalk
.. availability:: Unix.
.. versionadded:: 3.3
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. versionchanged:: 3.7
Added support for :class:`bytes` paths.
.. function:: memfd_create(name[, flags=os.MFD_CLOEXEC])
Create an anonymous file and return a file descriptor that refers to it.
*flags* must be one of the ``os.MFD_*`` constants available on the system
(or a bitwise ORed combination of them). By default, the new file
descriptor is :ref:`non-inheritable <fd_inheritance>`.
The name supplied in *name* is used as a filename and will be displayed as
the target of the corresponding symbolic link in the directory
``/proc/self/fd/``. The displayed name is always prefixed with ``memfd:``
and serves only for debugging purposes. Names do not affect the behavior of
the file descriptor, and as such multiple files can have the same name
without any side effects.
.. availability:: Linux >= 3.17 with glibc >= 2.27.
.. versionadded:: 3.8
.. data:: MFD_CLOEXEC
MFD_ALLOW_SEALING
MFD_HUGETLB
MFD_HUGE_SHIFT
MFD_HUGE_MASK
MFD_HUGE_64KB
MFD_HUGE_512KB
MFD_HUGE_1MB
MFD_HUGE_2MB
MFD_HUGE_8MB
MFD_HUGE_16MB
MFD_HUGE_32MB
MFD_HUGE_256MB
MFD_HUGE_512MB
MFD_HUGE_1GB
MFD_HUGE_2GB
MFD_HUGE_16GB
These flags can be passed to :func:`memfd_create`.
.. availability:: Linux >= 3.17 with glibc >= 2.27
The ``MFD_HUGE*`` flags are only available since Linux 4.14.
.. versionadded:: 3.8
.. function:: eventfd(initval[, flags=os.EFD_CLOEXEC])
Create and return an event file descriptor. The file descriptors supports
raw :func:`read` and :func:`write` with a buffer size of 8,
:func:`~select.select`, :func:`~select.poll` and similar. See man page
:manpage:`eventfd(2)` for more information. By default, the
new file descriptor is :ref:`non-inheritable <fd_inheritance>`.
*initval* is the initial value of the event counter. The initial value
must be a 32 bit unsigned integer. Please note that the initial value is
limited to a 32 bit unsigned int although the event counter is an unsigned
64 bit integer with a maximum value of 2\ :sup:`64`\ -\ 2.
*flags* can be constructed from :const:`EFD_CLOEXEC`,
:const:`EFD_NONBLOCK`, and :const:`EFD_SEMAPHORE`.
If :const:`EFD_SEMAPHORE` is specified and the event counter is non-zero,
:func:`eventfd_read` returns 1 and decrements the counter by one.
If :const:`EFD_SEMAPHORE` is not specified and the event counter is
non-zero, :func:`eventfd_read` returns the current event counter value and
resets the counter to zero.
If the event counter is zero and :const:`EFD_NONBLOCK` is not
specified, :func:`eventfd_read` blocks.
:func:`eventfd_write` increments the event counter. Write blocks if the
write operation would increment the counter to a value larger than
2\ :sup:`64`\ -\ 2.
Example::
import os
# semaphore with start value '1'
fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFC_CLOEXEC)
try:
# acquire semaphore
v = os.eventfd_read(fd)
try:
do_work()
finally:
# release semaphore
os.eventfd_write(fd, v)
finally:
os.close(fd)
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.10
.. function:: eventfd_read(fd)
Read value from an :func:`eventfd` file descriptor and return a 64 bit
unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
.. availability:: Linux >= 2.6.27
.. versionadded:: 3.10
.. function:: eventfd_write(fd, value)
Add value to an :func:`eventfd` file descriptor. *value* must be a 64 bit
unsigned int. The function does not verify that *fd* is an :func:`eventfd`.
.. availability:: Linux >= 2.6.27
.. versionadded:: 3.10
.. data:: EFD_CLOEXEC
Set close-on-exec flag for new :func:`eventfd` file descriptor.
.. availability:: Linux >= 2.6.27
.. versionadded:: 3.10
.. data:: EFD_NONBLOCK
Set :const:`O_NONBLOCK` status flag for new :func:`eventfd` file
descriptor.
.. availability:: Linux >= 2.6.27
.. versionadded:: 3.10
.. data:: EFD_SEMAPHORE
Provide semaphore-like semantics for reads from an :func:`eventfd` file
descriptor. On read the internal counter is decremented by one.
.. availability:: Linux >= 2.6.30
.. versionadded:: 3.10
.. _os-timerfd:
Timer File Descriptors
~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 3.13
These functions provide support for Linux's *timer file descriptor* API.
Naturally, they are all only available on Linux.
.. function:: timerfd_create(clockid, /, *, flags=0)
Create and return a timer file descriptor (*timerfd*).
The file descriptor returned by :func:`timerfd_create` supports:
- :func:`read`
- :func:`~select.select`
- :func:`~select.poll`
The file descriptor's :func:`read` method can be called with a buffer size
of 8. If the timer has already expired one or more times, :func:`read`
returns the number of expirations with the host's endianness, which may be
converted to an :class:`int` by ``int.from_bytes(x, byteorder=sys.byteorder)``.
:func:`~select.select` and :func:`~select.poll` can be used to wait until
timer expires and the file descriptor is readable.
*clockid* must be a valid :ref:`clock ID <time-clock-id-constants>`,
as defined in the :py:mod:`time` module:
- :const:`time.CLOCK_REALTIME`
- :const:`time.CLOCK_MONOTONIC`
- :const:`time.CLOCK_BOOTTIME` (Since Linux 3.15 for timerfd_create)
If *clockid* is :const:`time.CLOCK_REALTIME`, a settable system-wide
real-time clock is used. If system clock is changed, timer setting need
to be updated. To cancel timer when system clock is changed, see
:const:`TFD_TIMER_CANCEL_ON_SET`.
If *clockid* is :const:`time.CLOCK_MONOTONIC`, a non-settable monotonically
increasing clock is used. Even if the system clock is changed, the timer
setting will not be affected.
If *clockid* is :const:`time.CLOCK_BOOTTIME`, same as :const:`time.CLOCK_MONOTONIC`
except it includes any time that the system is suspended.
The file descriptor's behaviour can be modified by specifying a *flags* value.
Any of the following variables may used, combined using bitwise OR
(the ``|`` operator):
- :const:`TFD_NONBLOCK`
- :const:`TFD_CLOEXEC`
If :const:`TFD_NONBLOCK` is not set as a flag, :func:`read` blocks until
the timer expires. If it is set as a flag, :func:`read` doesn't block, but
If there hasn't been an expiration since the last call to read,
:func:`read` raises :class:`OSError` with ``errno`` is set to
:const:`errno.EAGAIN`.
:const:`TFD_CLOEXEC` is always set by Python automatically.
The file descriptor must be closed with :func:`os.close` when it is no
longer needed, or else the file descriptor will be leaked.
.. seealso:: The :manpage:`timerfd_create(2)` man page.
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. function:: timerfd_settime(fd, /, *, flags=flags, initial=0.0, interval=0.0)
Alter a timer file descriptor's internal timer.
This function operates the same interval timer as :func:`timerfd_settime_ns`.
*fd* must be a valid timer file descriptor.
The timer's behaviour can be modified by specifying a *flags* value.
Any of the following variables may used, combined using bitwise OR
(the ``|`` operator):
- :const:`TFD_TIMER_ABSTIME`
- :const:`TFD_TIMER_CANCEL_ON_SET`
The timer is disabled by setting *initial* to zero (``0``).
If *initial* is equal to or greater than zero, the timer is enabled.
If *initial* is less than zero, it raises an :class:`OSError` exception
with ``errno`` set to :const:`errno.EINVAL`
By default the timer will fire when *initial* seconds have elapsed.
(If *initial* is zero, timer will fire immediately.)
However, if the :const:`TFD_TIMER_ABSTIME` flag is set,
the timer will fire when the timer's clock
(set by *clockid* in :func:`timerfd_create`) reaches *initial* seconds.
The timer's interval is set by the *interval* :py:class:`float`.
If *interval* is zero, the timer only fires once, on the initial expiration.
If *interval* is greater than zero, the timer fires every time *interval*
seconds have elapsed since the previous expiration.
If *interval* is less than zero, it raises :class:`OSError` with ``errno``
set to :const:`errno.EINVAL`
If the :const:`TFD_TIMER_CANCEL_ON_SET` flag is set along with
:const:`TFD_TIMER_ABSTIME` and the clock for this timer is
:const:`time.CLOCK_REALTIME`, the timer is marked as cancelable if the
real-time clock is changed discontinuously. Reading the descriptor is
aborted with the error ECANCELED.
Linux manages system clock as UTC. A daylight-savings time transition is
done by changing time offset only and doesn't cause discontinuous system
clock change.
Discontinuous system clock change will be caused by the following events:
- ``settimeofday``
- ``clock_settime``
- set the system date and time by ``date`` command
Return a two-item tuple of (``next_expiration``, ``interval``) from
the previous timer state, before this function executed.
.. seealso::
:manpage:`timerfd_create(2)`, :manpage:`timerfd_settime(2)`,
:manpage:`settimeofday(2)`, :manpage:`clock_settime(2)`,
and :manpage:`date(1)`.
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. function:: timerfd_settime_ns(fd, /, *, flags=0, initial=0, interval=0)
Similar to :func:`timerfd_settime`, but use time as nanoseconds.
This function operates the same interval timer as :func:`timerfd_settime`.
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. function:: timerfd_gettime(fd, /)
Return a two-item tuple of floats (``next_expiration``, ``interval``).
``next_expiration`` denotes the relative time until next the timer next fires,
regardless of if the :const:`TFD_TIMER_ABSTIME` flag is set.
``interval`` denotes the timer's interval.
If zero, the timer will only fire once, after ``next_expiration`` seconds
have elapsed.
.. seealso:: :manpage:`timerfd_gettime(2)`
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. function:: timerfd_gettime_ns(fd, /)
Similar to :func:`timerfd_gettime`, but return time as nanoseconds.
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. data:: TFD_NONBLOCK
A flag for the :func:`timerfd_create` function,
which sets the :const:`O_NONBLOCK` status flag for the new timer file
descriptor. If :const:`TFD_NONBLOCK` is not set as a flag, :func:`read` blocks.
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. data:: TFD_CLOEXEC
A flag for the :func:`timerfd_create` function,
If :const:`TFD_CLOEXEC` is set as a flag, set close-on-exec flag for new file
descriptor.
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. data:: TFD_TIMER_ABSTIME
A flag for the :func:`timerfd_settime` and :func:`timerfd_settime_ns` functions.
If this flag is set, *initial* is interpreted as an absolute value on the
timer's clock (in UTC seconds or nanoseconds since the Unix Epoch).
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
.. data:: TFD_TIMER_CANCEL_ON_SET
A flag for the :func:`timerfd_settime` and :func:`timerfd_settime_ns`
functions along with :const:`TFD_TIMER_ABSTIME`.
The timer is cancelled when the time of the underlying clock changes
discontinuously.
.. availability:: Linux >= 2.6.27 with glibc >= 2.8
.. versionadded:: 3.13
Linux extended attributes
~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 3.3
These functions are all available on Linux only.
.. function:: getxattr(path, attribute, *, follow_symlinks=True)
Return the value of the extended filesystem attribute *attribute* for
*path*. *attribute* can be bytes or str (directly or indirectly through the
:class:`PathLike` interface). If it is str, it is encoded with the filesystem
encoding.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
.. audit-event:: os.getxattr path,attribute os.getxattr
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *path* and *attribute*.
.. function:: listxattr(path=None, *, follow_symlinks=True)
Return a list of the extended filesystem attributes on *path*. The
attributes in the list are represented as strings decoded with the filesystem
encoding. If *path* is ``None``, :func:`listxattr` will examine the current
directory.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
.. audit-event:: os.listxattr path os.listxattr
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: removexattr(path, attribute, *, follow_symlinks=True)
Removes the extended filesystem attribute *attribute* from *path*.
*attribute* should be bytes or str (directly or indirectly through the
:class:`PathLike` interface). If it is a string, it is encoded
with the :term:`filesystem encoding and error handler`.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
.. audit-event:: os.removexattr path,attribute os.removexattr
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *path* and *attribute*.
.. function:: setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
Set the extended filesystem attribute *attribute* on *path* to *value*.
*attribute* must be a bytes or str with no embedded NULs (directly or
indirectly through the :class:`PathLike` interface). If it is a str,
it is encoded with the :term:`filesystem encoding and error handler`. *flags* may be
:data:`XATTR_REPLACE` or :data:`XATTR_CREATE`. If :data:`XATTR_REPLACE` is
given and the attribute does not exist, ``ENODATA`` will be raised.
If :data:`XATTR_CREATE` is given and the attribute already exists, the
attribute will not be created and ``EEXISTS`` will be raised.
This function can support :ref:`specifying a file descriptor <path_fd>` and
:ref:`not following symlinks <follow_symlinks>`.
.. note::
A bug in Linux kernel versions less than 2.6.39 caused the flags argument
to be ignored on some filesystems.
.. audit-event:: os.setxattr path,attribute,value,flags os.setxattr
.. versionchanged:: 3.6
Accepts a :term:`path-like object` for *path* and *attribute*.
.. data:: XATTR_SIZE_MAX
The maximum size the value of an extended attribute can be. Currently, this
is 64 KiB on Linux.
.. data:: XATTR_CREATE
This is a possible value for the flags argument in :func:`setxattr`. It
indicates the operation must create an attribute.
.. data:: XATTR_REPLACE
This is a possible value for the flags argument in :func:`setxattr`. It
indicates the operation must replace an existing attribute.
.. _os-process:
Process Management
------------------
These functions may be used to create and manage processes.
The various :func:`exec\* <execl>` functions take a list of arguments for the new
program loaded into the process. In each case, the first of these arguments is
passed to the new program as its own name rather than as an argument a user may
have typed on a command line. For the C programmer, this is the ``argv[0]``
passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo',
['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
to be ignored.
.. function:: abort()
Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
behavior is to produce a core dump; on Windows, the process immediately returns
an exit code of ``3``. Be aware that calling this function will not call the
Python signal handler registered for :const:`SIGABRT` with
:func:`signal.signal`.
.. function:: add_dll_directory(path)
Add a path to the DLL search path.
This search path is used when resolving dependencies for imported
extension modules (the module itself is resolved through
:data:`sys.path`), and also by :mod:`ctypes`.
Remove the directory by calling **close()** on the returned object
or using it in a :keyword:`with` statement.
See the `Microsoft documentation
<https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5>`_
for more information about how DLLs are loaded.
.. audit-event:: os.add_dll_directory path os.add_dll_directory
.. availability:: Windows.
.. versionadded:: 3.8
Previous versions of CPython would resolve DLLs using the default
behavior for the current process. This led to inconsistencies,
such as only sometimes searching :envvar:`PATH` or the current
working directory, and OS functions such as ``AddDllDirectory``
having no effect.
In 3.8, the two primary ways DLLs are loaded now explicitly
override the process-wide behavior to ensure consistency. See the
:ref:`porting notes <bpo-36085-whatsnew>` for information on
updating libraries.
.. function:: execl(path, arg0, arg1, ...)
execle(path, arg0, arg1, ..., env)
execlp(file, arg0, arg1, ...)
execlpe(file, arg0, arg1, ..., env)
execv(path, args)
execve(path, args, env)
execvp(file, args)
execvpe(file, args, env)
These functions all execute a new program, replacing the current process; they
do not return. On Unix, the new executable is loaded into the current process,
and will have the same process id as the caller. Errors will be reported as
:exc:`OSError` exceptions.
The current process is replaced immediately. Open file objects and
descriptors are not flushed, so if there may be data buffered
on these open files, you should flush them using
:func:`sys.stdout.flush` or :func:`os.fsync` before calling an
:func:`exec\* <execl>` function.
The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
command-line arguments are passed. The "l" variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the :func:`!execl\*`
functions. The "v" variants are good when the number of parameters is
variable, with the arguments being passed in a list or tuple as the *args*
parameter. In either case, the arguments to the child process should start with
the name of the command being run, but this is not enforced.
The variants which include a "p" near the end (:func:`execlp`,
:func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
:envvar:`PATH` environment variable to locate the program *file*. When the
environment is being replaced (using one of the :func:`exec\*e <execl>` variants,
discussed in the next paragraph), the new environment is used as the source of
the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
:func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
locate the executable; *path* must contain an appropriate absolute or relative
path. Relative paths must include at least one slash, even on Windows, as
plain names will not be resolved.
For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
that these all end in "e"), the *env* parameter must be a mapping which is
used to define the environment variables for the new process (these are used
instead of the current process' environment); the functions :func:`execl`,
:func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
inherit the environment of the current process.
For :func:`execve` on some platforms, *path* may also be specified as an open
file descriptor. This functionality may not be supported on your platform;
you can check whether or not it is available using :data:`os.supports_fd`.
If it is unavailable, using it will raise a :exc:`NotImplementedError`.
.. audit-event:: os.exec path,args,env os.execl
.. availability:: Unix, Windows, not WASI, not Android, not iOS.
.. versionchanged:: 3.3
Added support for specifying *path* as an open file descriptor
for :func:`execve`.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. function:: _exit(n)
Exit the process with status *n*, without calling cleanup handlers, flushing
stdio buffers, etc.
.. note::
The standard way to exit is :func:`sys.exit(n) <sys.exit>`. :func:`!_exit` should
normally only be used in the child process after a :func:`fork`.
The following exit codes are defined and can be used with :func:`_exit`,
although they are not required. These are typically used for system programs
written in Python, such as a mail server's external command delivery program.
.. note::
Some of these may not be available on all Unix platforms, since there is some
variation. These constants are defined where they are defined by the underlying
platform.
.. data:: EX_OK
Exit code that means no error occurred. May be taken from the defined value of
``EXIT_SUCCESS`` on some platforms. Generally has a value of zero.
.. availability:: Unix, Windows.
.. data:: EX_USAGE
Exit code that means the command was used incorrectly, such as when the wrong
number of arguments are given.
.. availability:: Unix, not WASI.
.. data:: EX_DATAERR
Exit code that means the input data was incorrect.
.. availability:: Unix, not WASI.
.. data:: EX_NOINPUT
Exit code that means an input file did not exist or was not readable.
.. availability:: Unix, not WASI.
.. data:: EX_NOUSER
Exit code that means a specified user did not exist.
.. availability:: Unix, not WASI.
.. data:: EX_NOHOST
Exit code that means a specified host did not exist.
.. availability:: Unix, not WASI.
.. data:: EX_UNAVAILABLE
Exit code that means that a required service is unavailable.
.. availability:: Unix, not WASI.
.. data:: EX_SOFTWARE
Exit code that means an internal software error was detected.
.. availability:: Unix, not WASI.
.. data:: EX_OSERR
Exit code that means an operating system error was detected, such as the
inability to fork or create a pipe.
.. availability:: Unix, not WASI.
.. data:: EX_OSFILE
Exit code that means some system file did not exist, could not be opened, or had
some other kind of error.
.. availability:: Unix, not WASI.
.. data:: EX_CANTCREAT
Exit code that means a user specified output file could not be created.
.. availability:: Unix, not WASI.
.. data:: EX_IOERR
Exit code that means that an error occurred while doing I/O on some file.
.. availability:: Unix, not WASI.
.. data:: EX_TEMPFAIL
Exit code that means a temporary failure occurred. This indicates something
that may not really be an error, such as a network connection that couldn't be
made during a retryable operation.
.. availability:: Unix, not WASI.
.. data:: EX_PROTOCOL
Exit code that means that a protocol exchange was illegal, invalid, or not
understood.
.. availability:: Unix, not WASI.
.. data:: EX_NOPERM
Exit code that means that there were insufficient permissions to perform the
operation (but not intended for file system problems).
.. availability:: Unix, not WASI.
.. data:: EX_CONFIG
Exit code that means that some kind of configuration error occurred.
.. availability:: Unix, not WASI.
.. data:: EX_NOTFOUND
Exit code that means something like "an entry was not found".
.. availability:: Unix, not WASI.
.. function:: fork()
Fork a child process. Return ``0`` in the child and the child's process id in the
parent. If an error occurs :exc:`OSError` is raised.
Note that some platforms including FreeBSD <= 6.3 and Cygwin have
known issues when using ``fork()`` from a thread.
.. audit-event:: os.fork "" os.fork
.. warning::
If you use TLS sockets in an application calling ``fork()``, see
the warning in the :mod:`ssl` documentation.
.. warning::
On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using :mod:`urllib.request`.
.. versionchanged:: 3.8
Calling ``fork()`` in a subinterpreter is no longer supported
(:exc:`RuntimeError` is raised).
.. versionchanged:: 3.12
If Python is able to detect that your process has multiple
threads, :func:`os.fork` now raises a :exc:`DeprecationWarning`.
We chose to surface this as a warning, when detectable, to better
inform developers of a design problem that the POSIX platform
specifically notes as not supported. Even in code that
*appears* to work, it has never been safe to mix threading with
:func:`os.fork` on POSIX platforms. The CPython runtime itself has
always made API calls that are not safe for use in the child
process when threads existed in the parent (such as ``malloc`` and
``free``).
Users of macOS or users of libc or malloc implementations other
than those typically found in glibc to date are among those
already more likely to experience deadlocks running such code.
See `this discussion on fork being incompatible with threads
<https://discuss.python.org/t/33555>`_
for technical details of why we're surfacing this longstanding
platform compatibility problem to developers.
.. availability:: POSIX, not WASI, not Android, not iOS.
.. function:: forkpty()
Fork a child process, using a new pseudo-terminal as the child's controlling
terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
new child's process id in the parent, and *fd* is the file descriptor of the
master end of the pseudo-terminal. For a more portable approach, use the
:mod:`pty` module. If an error occurs :exc:`OSError` is raised.
.. audit-event:: os.forkpty "" os.forkpty
.. warning::
On macOS the use of this function is unsafe when mixed with using
higher-level system APIs, and that includes using :mod:`urllib.request`.
.. versionchanged:: 3.8
Calling ``forkpty()`` in a subinterpreter is no longer supported
(:exc:`RuntimeError` is raised).
.. versionchanged:: 3.12
If Python is able to detect that your process has multiple
threads, this now raises a :exc:`DeprecationWarning`. See the
longer explanation on :func:`os.fork`.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: kill(pid, sig, /)
.. index::
single: process; killing
single: process; signalling
Send signal *sig* to the process *pid*. Constants for the specific signals
available on the host platform are defined in the :mod:`signal` module.
Windows: The :const:`signal.CTRL_C_EVENT` and
:const:`signal.CTRL_BREAK_EVENT` signals are special signals which can
only be sent to console processes which share a common console window,
e.g., some subprocesses. Any other value for *sig* will cause the process
to be unconditionally killed by the TerminateProcess API, and the exit code
will be set to *sig*.
See also :func:`signal.pthread_kill`.
.. audit-event:: os.kill pid,sig os.kill
.. availability:: Unix, Windows, not WASI, not iOS.
.. versionchanged:: 3.2
Added Windows support.
.. function:: killpg(pgid, sig, /)
.. index::
single: process; killing
single: process; signalling
Send the signal *sig* to the process group *pgid*.
.. audit-event:: os.killpg pgid,sig os.killpg
.. availability:: Unix, not WASI, not iOS.
.. function:: nice(increment, /)
Add *increment* to the process's "niceness". Return the new niceness.
.. availability:: Unix, not WASI.
.. function:: pidfd_open(pid, flags=0)
Return a file descriptor referring to the process *pid* with *flags* set.
This descriptor can be used to perform process management without races
and signals.
See the :manpage:`pidfd_open(2)` man page for more details.
.. availability:: Linux >= 5.3, Android >= :func:`build-time <sys.getandroidapilevel>` API level 31
.. versionadded:: 3.9
.. data:: PIDFD_NONBLOCK
This flag indicates that the file descriptor will be non-blocking.
If the process referred to by the file descriptor has not yet terminated,
then an attempt to wait on the file descriptor using :manpage:`waitid(2)`
will immediately return the error :const:`~errno.EAGAIN` rather than blocking.
.. availability:: Linux >= 5.10
.. versionadded:: 3.12
.. function:: plock(op, /)
Lock program segments into memory. The value of *op* (defined in
``<sys/lock.h>``) determines which segments are locked.
.. availability:: Unix, not WASI, not iOS.
.. function:: popen(cmd, mode='r', buffering=-1)
Open a pipe to or from command *cmd*.
The return value is an open file object
connected to the pipe, which can be read or written depending on whether *mode*
is ``'r'`` (default) or ``'w'``.
The *buffering* argument have the same meaning as
the corresponding argument to the built-in :func:`open` function. The
returned file object reads or writes text strings rather than bytes.
The ``close`` method returns :const:`None` if the subprocess exited
successfully, or the subprocess's return code if there was an
error. On POSIX systems, if the return code is positive it
represents the return value of the process left-shifted by one
byte. If the return code is negative, the process was terminated
by the signal given by the negated value of the return code. (For
example, the return value might be ``- signal.SIGKILL`` if the
subprocess was killed.) On Windows systems, the return value
contains the signed integer return code from the child process.
On Unix, :func:`waitstatus_to_exitcode` can be used to convert the ``close``
method result (exit status) into an exit code if it is not ``None``. On
Windows, the ``close`` method result is directly the exit code
(or ``None``).
This is implemented using :class:`subprocess.Popen`; see that class's
documentation for more powerful ways to manage and communicate with
subprocesses.
.. availability:: not WASI, not Android, not iOS.
.. note::
The :ref:`Python UTF-8 Mode <utf8-mode>` affects encodings used
for *cmd* and pipe contents.
:func:`popen` is a simple wrapper around :class:`subprocess.Popen`.
Use :class:`subprocess.Popen` or :func:`subprocess.run` to
control options like encodings.
.. function:: posix_spawn(path, argv, env, *, file_actions=None, \
setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
setsigdef=(), scheduler=None)
Wraps the :c:func:`!posix_spawn` C library API for use from Python.
Most users should use :func:`subprocess.run` instead of :func:`posix_spawn`.
The positional-only arguments *path*, *args*, and *env* are similar to
:func:`execve`. *env* is allowed to be ``None``, in which case current
process' environment is used.
The *path* parameter is the path to the executable file. The *path* should
contain a directory. Use :func:`posix_spawnp` to pass an executable file
without directory.
The *file_actions* argument may be a sequence of tuples describing actions
to take on specific file descriptors in the child process between the C
library implementation's :c:func:`fork` and :c:func:`exec` steps.
The first item in each tuple must be one of the three type indicator
listed below describing the remaining tuple elements:
.. data:: POSIX_SPAWN_OPEN
(``os.POSIX_SPAWN_OPEN``, *fd*, *path*, *flags*, *mode*)
Performs ``os.dup2(os.open(path, flags, mode), fd)``.
.. data:: POSIX_SPAWN_CLOSE
(``os.POSIX_SPAWN_CLOSE``, *fd*)
Performs ``os.close(fd)``.
.. data:: POSIX_SPAWN_DUP2
(``os.POSIX_SPAWN_DUP2``, *fd*, *new_fd*)
Performs ``os.dup2(fd, new_fd)``.
.. data:: POSIX_SPAWN_CLOSEFROM
(``os.POSIX_SPAWN_CLOSEFROM``, *fd*)
Performs ``os.closerange(fd, INF)``.
These tuples correspond to the C library
:c:func:`!posix_spawn_file_actions_addopen`,
:c:func:`!posix_spawn_file_actions_addclose`,
:c:func:`!posix_spawn_file_actions_adddup2`, and
:c:func:`!posix_spawn_file_actions_addclosefrom_np` API calls used to prepare
for the :c:func:`!posix_spawn` call itself.
The *setpgroup* argument will set the process group of the child to the value
specified. If the value specified is 0, the child's process group ID will be
made the same as its process ID. If the value of *setpgroup* is not set, the
child will inherit the parent's process group ID. This argument corresponds
to the C library :c:macro:`!POSIX_SPAWN_SETPGROUP` flag.
If the *resetids* argument is ``True`` it will reset the effective UID and
GID of the child to the real UID and GID of the parent process. If the
argument is ``False``, then the child retains the effective UID and GID of
the parent. In either case, if the set-user-ID and set-group-ID permission
bits are enabled on the executable file, their effect will override the
setting of the effective UID and GID. This argument corresponds to the C
library :c:macro:`!POSIX_SPAWN_RESETIDS` flag.
If the *setsid* argument is ``True``, it will create a new session ID
for ``posix_spawn``. *setsid* requires :c:macro:`!POSIX_SPAWN_SETSID`
or :c:macro:`!POSIX_SPAWN_SETSID_NP` flag. Otherwise, :exc:`NotImplementedError`
is raised.
The *setsigmask* argument will set the signal mask to the signal set
specified. If the parameter is not used, then the child inherits the
parent's signal mask. This argument corresponds to the C library
:c:macro:`!POSIX_SPAWN_SETSIGMASK` flag.
The *sigdef* argument will reset the disposition of all signals in the set
specified. This argument corresponds to the C library
:c:macro:`!POSIX_SPAWN_SETSIGDEF` flag.
The *scheduler* argument must be a tuple containing the (optional) scheduler
policy and an instance of :class:`sched_param` with the scheduler parameters.
A value of ``None`` in the place of the scheduler policy indicates that is
not being provided. This argument is a combination of the C library
:c:macro:`!POSIX_SPAWN_SETSCHEDPARAM` and :c:macro:`!POSIX_SPAWN_SETSCHEDULER`
flags.
.. audit-event:: os.posix_spawn path,argv,env os.posix_spawn
.. versionadded:: 3.8
.. versionchanged:: 3.13
*env* parameter accepts ``None``.
``os.POSIX_SPAWN_CLOSEFROM`` is available on platforms where
:c:func:`!posix_spawn_file_actions_addclosefrom_np` exists.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: posix_spawnp(path, argv, env, *, file_actions=None, \
setpgroup=None, resetids=False, setsid=False, setsigmask=(), \
setsigdef=(), scheduler=None)
Wraps the :c:func:`!posix_spawnp` C library API for use from Python.
Similar to :func:`posix_spawn` except that the system searches
for the *executable* file in the list of directories specified by the
:envvar:`PATH` environment variable (in the same way as for ``execvp(3)``).
.. audit-event:: os.posix_spawn path,argv,env os.posix_spawnp
.. versionadded:: 3.8
.. availability:: POSIX, not WASI, not Android, not iOS.
See :func:`posix_spawn` documentation.
.. function:: register_at_fork(*, before=None, after_in_parent=None, \
after_in_child=None)
Register callables to be executed when a new child process is forked
using :func:`os.fork` or similar process cloning APIs.
The parameters are optional and keyword-only.
Each specifies a different call point.
* *before* is a function called before forking a child process.
* *after_in_parent* is a function called from the parent process
after forking a child process.
* *after_in_child* is a function called from the child process.
These calls are only made if control is expected to return to the
Python interpreter. A typical :mod:`subprocess` launch will not
trigger them as the child is not going to re-enter the interpreter.
Functions registered for execution before forking are called in
reverse registration order. Functions registered for execution
after forking (either in the parent or in the child) are called
in registration order.
Note that :c:func:`fork` calls made by third-party C code may not
call those functions, unless it explicitly calls :c:func:`PyOS_BeforeFork`,
:c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`.
There is no way to unregister a function.
.. availability:: Unix, not WASI, not Android, not iOS.
.. versionadded:: 3.7
.. function:: spawnl(mode, path, ...)
spawnle(mode, path, ..., env)
spawnlp(mode, file, ...)
spawnlpe(mode, file, ..., env)
spawnv(mode, path, args)
spawnve(mode, path, args, env)
spawnvp(mode, file, args)
spawnvpe(mode, file, args, env)
Execute the program *path* in a new process.
(Note that the :mod:`subprocess` module provides more powerful facilities for
spawning new processes and retrieving their results; using that module is
preferable to using these functions. Check especially the
:ref:`subprocess-replacements` section.)
If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
exits normally, or ``-signal``, where *signal* is the signal that killed the
process. On Windows, the process id will actually be the process handle, so can
be used with the :func:`waitpid` function.
Note on VxWorks, this function doesn't return ``-signal`` when the new process is
killed. Instead it raises OSError exception.
The "l" and "v" variants of the :func:`spawn\* <spawnl>` functions differ in how
command-line arguments are passed. The "l" variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the
:func:`!spawnl\*` functions. The "v" variants are good when the number of
parameters is variable, with the arguments being passed in a list or tuple as
the *args* parameter. In either case, the arguments to the child process must
start with the name of the command being run.
The variants which include a second "p" near the end (:func:`spawnlp`,
:func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
:envvar:`PATH` environment variable to locate the program *file*. When the
environment is being replaced (using one of the :func:`spawn\*e <spawnl>` variants,
discussed in the next paragraph), the new environment is used as the source of
the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
:func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
:envvar:`PATH` variable to locate the executable; *path* must contain an
appropriate absolute or relative path.
For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
(note that these all end in "e"), the *env* parameter must be a mapping
which is used to define the environment variables for the new process (they are
used instead of the current process' environment); the functions
:func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
the new process to inherit the environment of the current process. Note that
keys and values in the *env* dictionary must be strings; invalid keys or
values will cause the function to fail, with a return value of ``127``.
As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
equivalent::
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
.. audit-event:: os.spawn mode,path,args,env os.spawnl
.. availability:: Unix, Windows, not WASI, not Android, not iOS.
:func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and
:func:`spawnve` are not thread-safe on Windows; we advise you to use the
:mod:`subprocess` module instead.
.. versionchanged:: 3.6
Accepts a :term:`path-like object`.
.. data:: P_NOWAIT
P_NOWAITO
Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
functions. If either of these values is given, the :func:`spawn\* <spawnl>` functions
will return as soon as the new process has been created, with the process id as
the return value.
.. availability:: Unix, Windows.
.. data:: P_WAIT
Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
functions. If this is given as *mode*, the :func:`spawn\* <spawnl>` functions will not
return until the new process has run to completion and will return the exit code
of the process the run is successful, or ``-signal`` if a signal kills the
process.
.. availability:: Unix, Windows.
.. data:: P_DETACH
P_OVERLAY
Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
functions. These are less portable than those listed above. :const:`P_DETACH`
is similar to :const:`P_NOWAIT`, but the new process is detached from the
console of the calling process. If :const:`P_OVERLAY` is used, the current
process will be replaced; the :func:`spawn\* <spawnl>` function will not return.
.. availability:: Windows.
.. function:: startfile(path, [operation], [arguments], [cwd], [show_cmd])
Start a file with its associated application.
When *operation* is not specified, this acts like double-clicking
the file in Windows Explorer, or giving the file name as an argument to the
:program:`start` command from the interactive command shell: the file is opened
with whatever application (if any) its extension is associated.
When another *operation* is given, it must be a "command verb" that specifies
what should be done with the file. Common verbs documented by Microsoft are ``'open'``,
``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
``'find'`` (to be used on directories).
When launching an application, specify *arguments* to be passed as a single
string. This argument may have no effect when using this function to launch a
document.
The default working directory is inherited, but may be overridden by the *cwd*
argument. This should be an absolute path. A relative *path* will be resolved
against this argument.
Use *show_cmd* to override the default window style. Whether this has any
effect will depend on the application being launched. Values are integers as
supported by the Win32 :c:func:`!ShellExecute` function.
:func:`startfile` returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way to retrieve
the application's exit status. The *path* parameter is relative to the current
directory or *cwd*. If you want to use an absolute path, make sure the first
character is not a slash (``'/'``) Use :mod:`pathlib` or the
:func:`os.path.normpath` function to ensure that paths are properly encoded for
Win32.
To reduce interpreter startup overhead, the Win32 :c:func:`!ShellExecute`
function is not resolved until this function is first called. If the function
cannot be resolved, :exc:`NotImplementedError` will be raised.
.. audit-event:: os.startfile path,operation os.startfile
.. audit-event:: os.startfile/2 path,operation,arguments,cwd,show_cmd os.startfile
.. availability:: Windows.
.. versionchanged:: 3.10
Added the *arguments*, *cwd* and *show_cmd* arguments, and the
``os.startfile/2`` audit event.
.. function:: system(command)
Execute the command (a string) in a subshell. This is implemented by calling
the Standard C function :c:func:`system`, and has the same limitations.
Changes to :data:`sys.stdin`, etc. are not reflected in the environment of
the executed command. If *command* generates any output, it will be sent to
the interpreter standard output stream. The C standard does not
specify the meaning of the return value of the C function, so the return
value of the Python function is system-dependent.
On Unix, the return value is the exit status of the process encoded in the
format specified for :func:`wait`.
On Windows, the return value is that returned by the system shell after
running *command*. The shell is given by the Windows environment variable
:envvar:`COMSPEC`: it is usually :program:`cmd.exe`, which returns the exit
status of the command run; on systems using a non-native shell, consult your
shell documentation.
The :mod:`subprocess` module provides more powerful facilities for spawning
new processes and retrieving their results; using that module is preferable
to using this function. See the :ref:`subprocess-replacements` section in
the :mod:`subprocess` documentation for some helpful recipes.
On Unix, :func:`waitstatus_to_exitcode` can be used to convert the result
(exit status) into an exit code. On Windows, the result is directly the exit
code.
.. audit-event:: os.system command os.system
.. availability:: Unix, Windows, not WASI, not Android, not iOS.
.. function:: times()
Returns the current global process times.
The return value is an object with five attributes:
* :attr:`!user` - user time
* :attr:`!system` - system time
* :attr:`!children_user` - user time of all child processes
* :attr:`!children_system` - system time of all child processes
* :attr:`!elapsed` - elapsed real time since a fixed point in the past
For backwards compatibility, this object also behaves like a five-tuple
containing :attr:`!user`, :attr:`!system`, :attr:`!children_user`,
:attr:`!children_system`, and :attr:`!elapsed` in that order.
See the Unix manual page
:manpage:`times(2)` and `times(3) <https://man.freebsd.org/cgi/man.cgi?time(3)>`_ manual page on Unix or `the GetProcessTimes MSDN
<https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes>`_
on Windows. On Windows, only :attr:`!user` and :attr:`!system` are known; the other attributes are zero.
.. availability:: Unix, Windows.
.. versionchanged:: 3.3
Return type changed from a tuple to a tuple-like object
with named attributes.
.. function:: wait()
Wait for completion of a child process, and return a tuple containing its pid
and exit status indication: a 16-bit number, whose low byte is the signal number
that killed the process, and whose high byte is the exit status (if the signal
number is zero); the high bit of the low byte is set if a core file was
produced.
If there are no children that could be waited for, :exc:`ChildProcessError`
is raised.
:func:`waitstatus_to_exitcode` can be used to convert the exit status into an
exit code.
.. availability:: Unix, not WASI, not Android, not iOS.
.. seealso::
The other :func:`!wait*` functions documented below can be used to wait for the
completion of a specific child process and have more options.
:func:`waitpid` is the only one also available on Windows.
.. function:: waitid(idtype, id, options, /)
Wait for the completion of a child process.
*idtype* can be :data:`P_PID`, :data:`P_PGID`, :data:`P_ALL`, or (on Linux) :data:`P_PIDFD`.
The interpretation of *id* depends on it; see their individual descriptions.
*options* is an OR combination of flags. At least one of :data:`WEXITED`,
:data:`WSTOPPED` or :data:`WCONTINUED` is required;
:data:`WNOHANG` and :data:`WNOWAIT` are additional optional flags.
The return value is an object representing the data contained in the
:c:type:`siginfo_t` structure with the following attributes:
* :attr:`!si_pid` (process ID)
* :attr:`!si_uid` (real user ID of the child)
* :attr:`!si_signo` (always :const:`~signal.SIGCHLD`)
* :attr:`!si_status` (the exit status or signal number, depending on :attr:`!si_code`)
* :attr:`!si_code` (see :data:`CLD_EXITED` for possible values)
If :data:`WNOHANG` is specified and there are no matching children in the
requested state, ``None`` is returned.
Otherwise, if there are no matching children
that could be waited for, :exc:`ChildProcessError` is raised.
.. availability:: Unix, not WASI, not Android, not iOS.
.. versionadded:: 3.3
.. versionchanged:: 3.13
This function is now available on macOS as well.
.. function:: waitpid(pid, options, /)
The details of this function differ on Unix and Windows.
On Unix: Wait for completion of a child process given by process id *pid*, and
return a tuple containing its process id and exit status indication (encoded as
for :func:`wait`). The semantics of the call are affected by the value of the
integer *options*, which should be ``0`` for normal operation.
If *pid* is greater than ``0``, :func:`waitpid` requests status information for
that specific process. If *pid* is ``0``, the request is for the status of any
child in the process group of the current process. If *pid* is ``-1``, the
request pertains to any child of the current process. If *pid* is less than
``-1``, status is requested for any process in the process group ``-pid`` (the
absolute value of *pid*).
*options* is an OR combination of flags. If it contains :data:`WNOHANG` and
there are no matching children in the requested state, ``(0, 0)`` is
returned. Otherwise, if there are no matching children that could be waited
for, :exc:`ChildProcessError` is raised. Other options that can be used are
:data:`WUNTRACED` and :data:`WCONTINUED`.
On Windows: Wait for completion of a process given by process handle *pid*, and
return a tuple containing *pid*, and its exit status shifted left by 8 bits
(shifting makes cross-platform use of the function easier). A *pid* less than or
equal to ``0`` has no special meaning on Windows, and raises an exception. The
value of integer *options* has no effect. *pid* can refer to any process whose
id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
functions called with :const:`P_NOWAIT` return suitable process handles.
:func:`waitstatus_to_exitcode` can be used to convert the exit status into an
exit code.
.. availability:: Unix, Windows, not WASI, not Android, not iOS.
.. versionchanged:: 3.5
If the system call is interrupted and the signal handler does not raise an
exception, the function now retries the system call instead of raising an
:exc:`InterruptedError` exception (see :pep:`475` for the rationale).
.. function:: wait3(options)
Similar to :func:`waitpid`, except no process id argument is given and a
3-element tuple containing the child's process id, exit status indication,
and resource usage information is returned. Refer to
:func:`resource.getrusage` for details on resource usage information. The
*options* argument is the same as that provided to :func:`waitpid` and
:func:`wait4`.
:func:`waitstatus_to_exitcode` can be used to convert the exit status into an
exitcode.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: wait4(pid, options)
Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
process id, exit status indication, and resource usage information is
returned. Refer to :func:`resource.getrusage` for details on resource usage
information. The arguments to :func:`wait4` are the same as those provided
to :func:`waitpid`.
:func:`waitstatus_to_exitcode` can be used to convert the exit status into an
exitcode.
.. availability:: Unix, not WASI, not Android, not iOS.
.. data:: P_PID
P_PGID
P_ALL
P_PIDFD
These are the possible values for *idtype* in :func:`waitid`. They affect
how *id* is interpreted:
* :data:`!P_PID` - wait for the child whose PID is *id*.
* :data:`!P_PGID` - wait for any child whose progress group ID is *id*.
* :data:`!P_ALL` - wait for any child; *id* is ignored.
* :data:`!P_PIDFD` - wait for the child identified by the file descriptor
*id* (a process file descriptor created with :func:`pidfd_open`).
.. availability:: Unix, not WASI, not Android, not iOS.
.. note:: :data:`!P_PIDFD` is only available on Linux >= 5.4.
.. versionadded:: 3.3
.. versionadded:: 3.9
The :data:`!P_PIDFD` constant.
.. data:: WCONTINUED
This *options* flag for :func:`waitpid`, :func:`wait3`, :func:`wait4`, and
:func:`waitid` causes child processes to be reported if they have been
continued from a job control stop since they were last reported.
.. availability:: Unix, not WASI, not Android, not iOS.
.. data:: WEXITED
This *options* flag for :func:`waitid` causes child processes that have terminated to
be reported.
The other ``wait*`` functions always report children that have terminated,
so this option is not available for them.
.. availability:: Unix, not WASI, not Android, not iOS.
.. versionadded:: 3.3
.. data:: WSTOPPED
This *options* flag for :func:`waitid` causes child processes that have been stopped
by the delivery of a signal to be reported.
This option is not available for the other ``wait*`` functions.
.. availability:: Unix, not WASI, not Android, not iOS.
.. versionadded:: 3.3
.. data:: WUNTRACED
This *options* flag for :func:`waitpid`, :func:`wait3`, and :func:`wait4` causes
child processes to also be reported if they have been stopped but their
current state has not been reported since they were stopped.
This option is not available for :func:`waitid`.
.. availability:: Unix, not WASI, not Android, not iOS.
.. data:: WNOHANG
This *options* flag causes :func:`waitpid`, :func:`wait3`, :func:`wait4`, and
:func:`waitid` to return right away if no child process status is available
immediately.
.. availability:: Unix, not WASI, not Android, not iOS.
.. data:: WNOWAIT
This *options* flag causes :func:`waitid` to leave the child in a waitable state, so that
a later :func:`!wait*` call can be used to retrieve the child status information again.
This option is not available for the other ``wait*`` functions.
.. availability:: Unix, not WASI, not Android, not iOS.
.. data:: CLD_EXITED
CLD_KILLED
CLD_DUMPED
CLD_TRAPPED
CLD_STOPPED
CLD_CONTINUED
These are the possible values for :attr:`!si_code` in the result returned by
:func:`waitid`.
.. availability:: Unix, not WASI, not Android, not iOS.
.. versionadded:: 3.3
.. versionchanged:: 3.9
Added :data:`CLD_KILLED` and :data:`CLD_STOPPED` values.
.. function:: waitstatus_to_exitcode(status)
Convert a wait status to an exit code.
On Unix:
* If the process exited normally (if ``WIFEXITED(status)`` is true),
return the process exit status (return ``WEXITSTATUS(status)``):
result greater than or equal to 0.
* If the process was terminated by a signal (if ``WIFSIGNALED(status)`` is
true), return ``-signum`` where *signum* is the number of the signal that
caused the process to terminate (return ``-WTERMSIG(status)``):
result less than 0.
* Otherwise, raise a :exc:`ValueError`.
On Windows, return *status* shifted right by 8 bits.
On Unix, if the process is being traced or if :func:`waitpid` was called
with :data:`WUNTRACED` option, the caller must first check if
``WIFSTOPPED(status)`` is true. This function must not be called if
``WIFSTOPPED(status)`` is true.
.. seealso::
:func:`WIFEXITED`, :func:`WEXITSTATUS`, :func:`WIFSIGNALED`,
:func:`WTERMSIG`, :func:`WIFSTOPPED`, :func:`WSTOPSIG` functions.
.. availability:: Unix, Windows, not WASI, not Android, not iOS.
.. versionadded:: 3.9
The following functions take a process status code as returned by
:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
used to determine the disposition of a process.
.. function:: WCOREDUMP(status, /)
Return ``True`` if a core dump was generated for the process, otherwise
return ``False``.
This function should be employed only if :func:`WIFSIGNALED` is true.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: WIFCONTINUED(status)
Return ``True`` if a stopped child has been resumed by delivery of
:const:`~signal.SIGCONT` (if the process has been continued from a job
control stop), otherwise return ``False``.
See :data:`WCONTINUED` option.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: WIFSTOPPED(status)
Return ``True`` if the process was stopped by delivery of a signal,
otherwise return ``False``.
:func:`WIFSTOPPED` only returns ``True`` if the :func:`waitpid` call was
done using :data:`WUNTRACED` option or when the process is being traced (see
:manpage:`ptrace(2)`).
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: WIFSIGNALED(status)
Return ``True`` if the process was terminated by a signal, otherwise return
``False``.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: WIFEXITED(status)
Return ``True`` if the process exited terminated normally, that is,
by calling ``exit()`` or ``_exit()``, or by returning from ``main()``;
otherwise return ``False``.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: WEXITSTATUS(status)
Return the process exit status.
This function should be employed only if :func:`WIFEXITED` is true.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: WSTOPSIG(status)
Return the signal which caused the process to stop.
This function should be employed only if :func:`WIFSTOPPED` is true.
.. availability:: Unix, not WASI, not Android, not iOS.
.. function:: WTERMSIG(status)
Return the number of the signal that caused the process to terminate.
This function should be employed only if :func:`WIFSIGNALED` is true.
.. availability:: Unix, not WASI, not Android, not iOS.
Interface to the scheduler
--------------------------
These functions control how a process is allocated CPU time by the operating
system. They are only available on some Unix platforms. For more detailed
information, consult your Unix manpages.
.. versionadded:: 3.3
The following scheduling policies are exposed if they are supported by the
operating system.
.. _os-scheduling-policy:
.. data:: SCHED_OTHER
The default scheduling policy.
.. data:: SCHED_BATCH
Scheduling policy for CPU-intensive processes that tries to preserve
interactivity on the rest of the computer.
.. data:: SCHED_IDLE
Scheduling policy for extremely low priority background tasks.
.. data:: SCHED_SPORADIC
Scheduling policy for sporadic server programs.
.. data:: SCHED_FIFO
A First In First Out scheduling policy.
.. data:: SCHED_RR
A round-robin scheduling policy.
.. data:: SCHED_RESET_ON_FORK
This flag can be OR'ed with any other scheduling policy. When a process with
this flag set forks, its child's scheduling policy and priority are reset to
the default.
.. class:: sched_param(sched_priority)
This class represents tunable scheduling parameters used in
:func:`sched_setparam`, :func:`sched_setscheduler`, and
:func:`sched_getparam`. It is immutable.
At the moment, there is only one possible parameter:
.. attribute:: sched_priority
The scheduling priority for a scheduling policy.
.. function:: sched_get_priority_min(policy)
Get the minimum priority value for *policy*. *policy* is one of the
scheduling policy constants above.
.. function:: sched_get_priority_max(policy)
Get the maximum priority value for *policy*. *policy* is one of the
scheduling policy constants above.
.. function:: sched_setscheduler(pid, policy, param, /)
Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means
the calling process. *policy* is one of the scheduling policy constants
above. *param* is a :class:`sched_param` instance.
.. function:: sched_getscheduler(pid, /)
Return the scheduling policy for the process with PID *pid*. A *pid* of 0
means the calling process. The result is one of the scheduling policy
constants above.
.. function:: sched_setparam(pid, param, /)
Set the scheduling parameters for the process with PID *pid*. A *pid* of 0 means
the calling process. *param* is a :class:`sched_param` instance.
.. function:: sched_getparam(pid, /)
Return the scheduling parameters as a :class:`sched_param` instance for the
process with PID *pid*. A *pid* of 0 means the calling process.
.. function:: sched_rr_get_interval(pid, /)
Return the round-robin quantum in seconds for the process with PID *pid*. A
*pid* of 0 means the calling process.
.. function:: sched_yield()
Voluntarily relinquish the CPU. See :manpage:`sched_yield(2)` for details.
.. function:: sched_setaffinity(pid, mask, /)
Restrict the process with PID *pid* (or the current process if zero) to a
set of CPUs. *mask* is an iterable of integers representing the set of
CPUs to which the process should be restricted.
.. function:: sched_getaffinity(pid, /)
Return the set of CPUs the process with PID *pid* is restricted to.
If *pid* is zero, return the set of CPUs the calling thread of the current
process is restricted to.
See also the :func:`process_cpu_count` function.
.. _os-path:
Miscellaneous System Information
--------------------------------
.. function:: confstr(name, /)
Return string-valued system configuration values. *name* specifies the
configuration value to retrieve; it may be a string which is the name of a
defined system value; these names are specified in a number of standards (POSIX,
Unix 95, Unix 98, and others). Some platforms define additional names as well.
The names known to the host operating system are given as the keys of the
``confstr_names`` dictionary. For configuration variables not included in that
mapping, passing an integer for *name* is also accepted.
If the configuration value specified by *name* isn't defined, ``None`` is
returned.
If *name* is a string and is not known, :exc:`ValueError` is raised. If a
specific value for *name* is not supported by the host system, even if it is
included in ``confstr_names``, an :exc:`OSError` is raised with
:const:`errno.EINVAL` for the error number.
.. availability:: Unix.
.. data:: confstr_names
Dictionary mapping names accepted by :func:`confstr` to the integer values
defined for those names by the host operating system. This can be used to
determine the set of names known to the system.
.. availability:: Unix.
.. function:: cpu_count()
Return the number of logical CPUs in the **system**. Returns ``None`` if
undetermined.
The :func:`process_cpu_count` function can be used to get the number of
logical CPUs usable by the calling thread of the **current process**.
.. versionadded:: 3.4
.. versionchanged:: 3.13
If :option:`-X cpu_count <-X>` is given or :envvar:`PYTHON_CPU_COUNT` is set,
:func:`cpu_count` returns the overridden value *n*.
.. function:: getloadavg()
Return the number of processes in the system run queue averaged over the last
1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
unobtainable.
.. availability:: Unix.
.. function:: process_cpu_count()
Get the number of logical CPUs usable by the calling thread of the **current
process**. Returns ``None`` if undetermined. It can be less than
:func:`cpu_count` depending on the CPU affinity.
The :func:`cpu_count` function can be used to get the number of logical CPUs
in the **system**.
If :option:`-X cpu_count <-X>` is given or :envvar:`PYTHON_CPU_COUNT` is set,
:func:`process_cpu_count` returns the overridden value *n*.
See also the :func:`sched_getaffinity` function.
.. versionadded:: 3.13
.. function:: sysconf(name, /)
Return integer-valued system configuration values. If the configuration value
specified by *name* isn't defined, ``-1`` is returned. The comments regarding
the *name* parameter for :func:`confstr` apply here as well; the dictionary that
provides information on the known names is given by ``sysconf_names``.
.. availability:: Unix.
.. data:: sysconf_names
Dictionary mapping names accepted by :func:`sysconf` to the integer values
defined for those names by the host operating system. This can be used to
determine the set of names known to the system.
.. availability:: Unix.
.. versionchanged:: 3.11
Add ``'SC_MINSIGSTKSZ'`` name.
The following data values are used to support path manipulation operations. These
are defined for all platforms.
Higher-level operations on pathnames are defined in the :mod:`os.path` module.
.. index:: single: . (dot); in pathnames
.. data:: curdir
The constant string used by the operating system to refer to the current
directory. This is ``'.'`` for Windows and POSIX. Also available via
:mod:`os.path`.
.. index:: single: ..; in pathnames
.. data:: pardir
The constant string used by the operating system to refer to the parent
directory. This is ``'..'`` for Windows and POSIX. Also available via
:mod:`os.path`.
.. index:: single: / (slash); in pathnames
.. index:: single: \ (backslash); in pathnames (Windows)
.. data:: sep
The character used by the operating system to separate pathname components.
This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
is not sufficient to be able to parse or concatenate pathnames --- use
:func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
useful. Also available via :mod:`os.path`.
.. index:: single: / (slash); in pathnames
.. data:: altsep
An alternative character used by the operating system to separate pathname
components, or ``None`` if only one separator character exists. This is set to
``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
:mod:`os.path`.
.. index:: single: . (dot); in pathnames
.. data:: extsep
The character which separates the base filename from the extension; for example,
the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
.. index:: single: : (colon); path separator (POSIX)
single: ; (semicolon)
.. data:: pathsep
The character conventionally used by the operating system to separate search
path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
Windows. Also available via :mod:`os.path`.
.. data:: defpath
The default search path used by :func:`exec\*p\* <execl>` and
:func:`spawn\*p\* <spawnl>` if the environment doesn't have a ``'PATH'``
key. Also available via :mod:`os.path`.
.. data:: linesep
The string used to separate (or, rather, terminate) lines on the current
platform. This may be a single character, such as ``'\n'`` for POSIX, or
multiple characters, for example, ``'\r\n'`` for Windows. Do not use
*os.linesep* as a line terminator when writing files opened in text mode (the
default); use a single ``'\n'`` instead, on all platforms.
.. data:: devnull
The file path of the null device. For example: ``'/dev/null'`` for
POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`.
.. data:: RTLD_LAZY
RTLD_NOW
RTLD_GLOBAL
RTLD_LOCAL
RTLD_NODELETE
RTLD_NOLOAD
RTLD_DEEPBIND
Flags for use with the :func:`~sys.setdlopenflags` and
:func:`~sys.getdlopenflags` functions. See the Unix manual page
:manpage:`dlopen(3)` for what the different flags mean.
.. versionadded:: 3.3
Random numbers
--------------
.. function:: getrandom(size, flags=0)
Get up to *size* random bytes. The function can return less bytes than
requested.
These bytes can be used to seed user-space random number generators or for
cryptographic purposes.
``getrandom()`` relies on entropy gathered from device drivers and other
sources of environmental noise. Unnecessarily reading large quantities of
data will have a negative impact on other users of the ``/dev/random`` and
``/dev/urandom`` devices.
The flags argument is a bit mask that can contain zero or more of the
following values ORed together: :py:const:`os.GRND_RANDOM` and
:py:data:`GRND_NONBLOCK`.
See also the `Linux getrandom() manual page
<https://man7.org/linux/man-pages/man2/getrandom.2.html>`_.
.. availability:: Linux >= 3.17.
.. versionadded:: 3.6
.. function:: urandom(size, /)
Return a bytestring of *size* random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The
returned data should be unpredictable enough for cryptographic applications,
though its exact quality depends on the OS implementation.
On Linux, if the ``getrandom()`` syscall is available, it is used in
blocking mode: block until the system urandom entropy pool is initialized
(128 bits of entropy are collected by the kernel). See the :pep:`524` for
the rationale. On Linux, the :func:`getrandom` function can be used to get
random bytes in non-blocking mode (using the :data:`GRND_NONBLOCK` flag) or
to poll until the system urandom entropy pool is initialized.
On a Unix-like system, random bytes are read from the ``/dev/urandom``
device. If the ``/dev/urandom`` device is not available or not readable, the
:exc:`NotImplementedError` exception is raised.
On Windows, it will use ``BCryptGenRandom()``.
.. seealso::
The :mod:`secrets` module provides higher level functions. For an
easy-to-use interface to the random number generator provided by your
platform, please see :class:`random.SystemRandom`.
.. versionchanged:: 3.5
On Linux 3.17 and newer, the ``getrandom()`` syscall is now used
when available. On OpenBSD 5.6 and newer, the C ``getentropy()``
function is now used. These functions avoid the usage of an internal file
descriptor.
.. versionchanged:: 3.5.2
On Linux, if the ``getrandom()`` syscall blocks (the urandom entropy pool
is not initialized yet), fall back on reading ``/dev/urandom``.
.. versionchanged:: 3.6
On Linux, ``getrandom()`` is now used in blocking mode to increase the
security.
.. versionchanged:: 3.11
On Windows, ``BCryptGenRandom()`` is used instead of ``CryptGenRandom()``
which is deprecated.
.. data:: GRND_NONBLOCK
By default, when reading from ``/dev/random``, :func:`getrandom` blocks if
no random bytes are available, and when reading from ``/dev/urandom``, it blocks
if the entropy pool has not yet been initialized.
If the :py:data:`GRND_NONBLOCK` flag is set, then :func:`getrandom` does not
block in these cases, but instead immediately raises :exc:`BlockingIOError`.
.. versionadded:: 3.6
.. data:: GRND_RANDOM
If this bit is set, then random bytes are drawn from the
``/dev/random`` pool instead of the ``/dev/urandom`` pool.
.. versionadded:: 3.6
|