Системные команды с помощью Python (os.system())
Возможно, нам потребуется интегрировать функции для выполнения некоторых задач системного администрирования в Python. К ним относятся поиск файлов, выполнение некоторых команд оболочки, выполнение некоторой расширенной обработки файлов и т. д. И для этого нам нужен какой-то способ взаимодействия между системой и интерпретатором Python.
Выполнение командных строк с помощью Python можно легко выполнить с помощью некоторых системных методов из os module .
Но с появлением модуля subprocess (с намерением заменить некоторые старые модули) доступ к командной строке стал намного проще в использовании. А также для управления выводом и избежания некоторых ограничений традиционных методов.
Выполнение команд оболочки в Python
Теперь, когда мы узнали о системных командах в Python. Давайте посмотрим, как мы можем реализовать то же самое.
1. Использование метода os.system()
Как указывалось ранее, выполнение команд оболочки в Python можно легко выполнить с помощью некоторых методов модуля os . Здесь мы собираемся использовать широко используемый os.system() .
Эта функция реализована с использованием функции C system() и, следовательно, имеет те же ограничения.
Метод принимает системную команду как строку на входе и возвращает код вывода.
В приведенном ниже примере мы пытаемся проверить версию Python в нашей системе с помощью командной строки.
Здесь res сохраняет возвращенное значение (код выхода = 0 для успеха). Из выходных данных видно, что команда выполнена успешно, и мы получили нашу версию Python, как и ожидалось.
2. Использование модуля подпроцесса
Модуль subprocess поставляется с различными полезными методами или функциями для создания новых процессов, подключения к их каналам ввода / вывода / ошибок и получения их кодов возврата.
В этом руководстве мы рассматриваем методы call() и check_output() поскольку они просты в использовании и надежны. Но для получения дополнительной информации вы всегда можете обратиться к официальной документации.
2.1. Метод call()
Теперь перейдем к методу subprocess.call() .
Метод call() принимает аргументы командной строки, переданные в виде списка строк или с аргументом оболочки, установленным в True . И возвращает нам код выхода или статус.
В приведенном ниже фрагменте кода мы пытаемся установить pandas с помощью PIP из оболочки.
Как видим, команда выполнена успешно с zero возвращаемым значением.
2.2. Метод check_output()
Вышеупомянутые методы выполняют успешно переданную команду оболочки, но не дают пользователю свободы манипулировать способом получения вывода. Для этого на check_output() должен check_output() метод подпроцесса check_output() .
Метод выполняет переданную команду, но вместо возврата статуса выхода на этот раз возвращает bytes объект.
Присмотритесь к приведенному ниже примеру, где мы снова пытаемся установить модуль pymysql (уже установленный).
Здесь, как и в предыдущих случаях, res хранит объект, возвращаемый методом check_output() . Мы видим, что type(res) подтверждает, что объект имеет bytes тип.
После этого печатаем декодированную строку и видим, что команда успешно выполнена.
Вывод
Итак, сегодня мы узнали, как мы можем выполнять системные команды с помощью системной команды Python (os.system()) и модуля подпроцесса. Мы рассмотрели здесь еще несколько команд, связанных с Python, но стоит отметить, что методы этим не ограничиваются.
Мы рекомендуем попробовать другие команды, используя описанные выше методы, чтобы лучше понять.
Если у вас возникнут дополнительные вопросы, оставляйте комментарии ниже.
Ссылки
- Документация подпроцесса Python
- Документация по ОС Python,
- Системная команда Python — os.system(), subprocess.call() — статья о Journal Dev
-
Генерация случайных целых чисел с помощью Python randint()
Учебник Python MySQL — Полное руководство
Генерация случайных целых чисел с помощью Python randint()
Free up drive space in Windows 10
If your PC is running low on free space, you might not be able to install important Windows updates, and your PC’s performance may be affected. Here are some ways to free up space so you can keep your PC up to date and running smoothly. These suggestions are listed in order, so start with the first one, see if that helps, and then continue to the next one if it doesn’t.
To check the total disk space left on your Windows 10 device, select File Explorer from the taskbar, and then select This PC on the left. The available space on your drive will appear under Devices and drives.
Note: If you follow the steps below and continue to have trouble updating Windows because of low disk space, resetting or reinstalling Windows might help. For more info, see Reinstall Windows 10.
If you used Disk Cleanup to free up space on your device and then see a Low Disk Space error, it’s possible that your Temp folder is quickly filling up with application (.appx) files that are used by Microsoft Store. For more info, see Low Disk Space error due to a full Temp folder.
Storage Sense can automatically free up drive space for you by getting rid of items that you don’t need, like temporary files and items in your Recycle Bin. For more info, see Manage drive space with Storage Sense.
If your system doesn’t have Storage sense, you can use the Disk Cleanup tool to delete temporary files and system files from your device.
In the search box on the taskbar, type disk cleanup, then select itfrom the results.
Select the check box next to the type of files you want to delete. (To view a description of each type of file, select the name.) By default, Downloaded Program Files, Temporary Internet Files, and Thumbnails are selected. Be sure to clear those check boxes if you don’t want to delete those files.
To free up even more space, select Clean up system files, and then select the type of system files you want to delete. Disk Cleanup will take a few moments to calculate the amount of space that can be freed up.
Note: If it’s been fewer than 10 days since you upgraded to Windows 10, your previous version of Windows will be listed as a system file you can delete. If you need to free up drive space, you can delete it, but keep in mind that you’ll be deleting your Windows.old folder, which contains files that give you the option to go back to your previous version of Windows. If you delete your previous version of Windows, this can’t be undone. (You won’t be able to go back to your previous version of Windows.)
After you’ve selected the types of files you want to delete, select OK, and then select Delete files in the confirmation window to start the cleanup.
There’s also an option in Disk Cleanup to Compress your OS drive. Selecting this option compresses the drive on which Windows is installed, helping you gain extra space to install important updates. This action does not delete the contents of this drive, and you shouldn’t experience problems opening and saving files from the compressed drive.
After you install the update, you can manually decompress the OS drive at any time. To do this, select File Explorer from the taskbar, and in the left pane, select This PC. Right-click or tap and hold the OS drive (usually disk C), and then select Properties on the shortcut menu. Clear the Compress this drive to save disk space check box, and then select Apply > OK.
Windows 10 may indicate that it needs more space to get the latest Windows 10 feature update. You can use an external storage device to help you complete the update.
Note: You may need to use a micro-USB adapter if your device doesn’t have a standard USB port.
Personal files such as videos, music, photos, and documents can take up a lot of space on your device. To see which files are using the most space:
Select File Explorer from the taskbar and find the files you want to move.
Under This PC in the menu on the left, select a folder to see what files are saved in it. The Videos, Music, Pictures, and Downloads folders usually contain the largest files that you’ve saved to your device.
To see the size of the files in a folder, select View > Details. Right-click in the open space and then select Sort by > Size to show the largest files at the top of the list.
If there are files you no longer need on your device, you can either delete them or move them to an external storage device like a USB drive or an SD card.
Note: If you delete any files, remember to empty the Recycle Bin to completely remove them from your device and free up space.
To move photos, music, videos, or other files that you want to keep but don’t use very often, consider saving them to an external storage device like a USB drive or an SD card. You’ll still be able to use them when the drive is connected, but they won’t take up space on your PC.
Connect an external storage device like a USB drive or SD card to your PC.
Select File Explorer from the taskbar and go to the folder that contains the files you want to move.
Select the files, select the Home tab, and then select Move to > Choose location.
Select the external storage device you connected in the location list, and then select Move.
Saving new files to another drive will help prevent low space problems on that drive in the future, so you won’t have to move your files to another drive repeatedly. Instead of saving all your new files to the default drive, you can save some of them to a different drive that has more free space.
Under More storage settings, select Change where new content is saved.
For each content type, select a drive from the drop-down menu. If the drive you want to use isn’t listed there, make sure it’s connected to your PC.
Note: OneDrive Files On-Demand requires Windows 10 version 1709 or later and OneDrive client version 17.3.7064.1005 or later. To see which version of Windows you’re running, select Start > Settings > System > About . To see which version of the OneDrive client you have installed, see Which version of OneDrive am I using?
Open About settingsYou can save space by turning on OneDrive Files On-Demand, which stores a smaller placeholder file on your hard drive instead of the full-size file that’s stored in your OneDrive account in the cloud. You’ll be able to get to your OneDrive files from your PC without having to use up hard-drive space downloading full-size versions of them all. See Learn about OneDrive Files On-Demand for more info.
Sometimes a virus or other malware can consume significant hard-drive space by corrupting your system files. If you suspect your PC is infected with malware, use an antivirus program like Windows Defender to run a virus scan and cleanup. If this doesn’t fix the problem, you might need to reset your PC.
If you’ve followed the instructions here but still need help freeing up space on your device, you can contact Microsoft support to chat with a support agent. This is also recommended if your attempts to free up drive space trigger particular error codes that you need help resolving.
The following questions concern low disk space and Windows Update specifically. Learn more about Windows Update.
When there isn’t enough free space available to install an update, a pop-up notification will prompt you that additional space is required to install the update.
When you select Fix issues, you’ll be informed about how much additional space is needed. You’ll also be notified that you can use an external storage device so that you don’t need to free up quite as much space on your system drive. Learn how to free up space to install Windows updates.
The total free disk space your device requires to complete an update varies. Typically, feature updates require 6 GB–11 GB or more of free space, while quality updates require 2 GB–3 GB or more. Learn about the difference between a feature update and a quality update.
You need disk space to download the update, download new versions of any optional features and languages that are currently installed, and to apply the update. Additional space is temporarily required to support removal of the update (typically for 10 days). This space can be reclaimed after the update is completed. To do this, Select Start > Settings > System > Storage > Free up space now.
Open Storage settingsThe update is compressed to reduce download size.
Note: For devices with reserved storage, an update will first use the reserved storage space before using other disk space. For more info, see How reserved storage works in Windows 10.
The space required to complete a feature update depends on two factors: which update path is followed and the size of optional content and other updates that apply to your PC when the feature update is installed.
Note: For devices with reserved storage, an update will first use the reserved storage space before using other disk space. For more info, see How reserved storage works in Windows 10.
Windows follows three different feature update paths, depending on the amount of disk space currently available.
1. For PCs with plenty of free disk space
Windows automatically tries to complete more of the update process in the background while you use your PC. This significantly reduces the time your PC will be offline (or unusable) during the update, although it might temporarily use more disk space to complete the update. Learn more about our efforts to reduce offline time during updates (English only at this time).
2. For PCs with limited free space but still enough to complete the update automatically
Windows will automatically optimize for reducing the amount of free disk space required to install the update. This will result in a longer offline install time.
3. For PCs that don’t have enough space to automatically install the update
Windows will prompt you to free up disk space or use external storage to temporarily extend the storage on your PC. If you use an external storage device, Windows won’t need as much free space on the system drive as it temporarily uses your external storage.
Across each of these update paths, the total amount of free disk space required will vary, depending on the optional content installed and other updates that apply to your PC. For example:
Optional features. Many optional features available for Windows are pre-installed or acquired on demand by the system, or manually by you. You can see which ones are installed on your PC by going to Settings > Apps > Apps & features > Manage optional features.
Open Optional features settings
These features range in size from less than 1 MB to almost 2 GB for the Windows Mixed Reality portal. You can reduce the amount of space required to install a feature update on your PC by uninstalling optional features you aren’t using.Languages installed. Windows is localized into many languages. Although many people only use one language at a time, some people switch between two or more languages. You can see which languages are installed on your PC by selecting Start > Settings > Time & Language > Language .
Open Language settings
During each update, all language resources and any associated typing, text-to-speech, speech-to-text, and handwriting recognition resources must be updated. The content for each language can range from about 175 MB to more than 300 MB. You can reduce the amount of space required to install a feature update on your PC by uninstalling languages you aren’t using.Driver updates. OEMs and other hardware partners sometimes publish new graphics, networking, audio, and other drivers in conjunction with the new OS update. The size of these drivers can vary significantly, depending on your PC and on which drivers have been updated.
OS quality updates. During a feature update, Windows tries to download and automatically install the latest quality update so that your PC is fully up to date when you start using it. Shortly after the feature update is released, the quality update for that feature update could be as small as a few hundred MB, but as more quality and security changes are implemented, the quality update can increase in size to 1 GB or more.If your PC is short on disk space, you can download and install the quality update after the feature update is complete.
Finally, Windows Update will temporarily disable hiberfile.sys, pagefile.sys, and other system files in order to use the space these files typically consume to apply the feature update. Any files that are disabled to apply the update will be automatically re-enabled when the update is complete. Because these files vary in size depending on how you use your PC and the amount of RAM your PC has, even in cases where two different PCs have the exact same OS image, the amount of free disk space required to complete an update may vary.
The combination of update path and features means there’s a wide range of free disk space required to complete an update. Here are a few examples for PCs updating to Windows version 1803:
Optimized for reduced offline time
Optimized for minimal disk space
Optimized for minimal disk space with external storage
Minimal optional features, languages, and updates