Взаимодействие с компьютером через интерфейс командной строки (CLI) - мощный метод, так как он значительно повышает производительность во время разработки. Фактически, владение командной строкой является обязательным для каждого программиста или специалиста по данным.
Я использую CLI с первых дней программирования, в основном для установки библиотек или выполнения команд Python. Но по мере того, как я изучаю новые команды, особенно за пределами области программирования, я влюбляюсь в интерфейс командной строки больше, чем когда-либо. Ниже приведен тщательно подобранный список из ПЯТИ любимых команд, которые, я уверен, вам всем тоже понравятся:
1. СКАЧАТЬ ВИДЕО
Скачивайте видео + аудио как отдельные файлы, так и целые плейлисты. youtube-dl - это программа командной строки, которая позволяет загружать видео с YouTube и других сайтов, таких как Vimeo. Для этого требуется интерпретатор Python версии 2.6, 2.7 или 3.2+, он не зависит от платформы и работает на вашем Unix-компьютере, в Windows или macOS.
Установка:
Вы можете скачать youtube-dl и скопировать его в / usr / local / bin /. Он размещен в открытом доступе на github, что означает, что вы можете его модифицировать, распространять или использовать как угодно.
sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl sudo chmod a+rx /usr/local/bin/youtube-dl
В качестве альтернативы вы также можете использовать pip:
sudo -H pip install --upgrade youtube-dl
Синтаксис:
youtube-dl [OPTIONS] URL [URL...] Options -F, --list-formats List all available formats. -f, --format FORMAT Video format code, see example below. -i, --ignore-errors Continue on download errors, for example to skip unavailable videos in a playlist. --abort-on-error Cancel downloading of further videos (in the playlist or the command line) if an error occurs. --no-playlist Download only the video, if the URL refers to a video and a playlist. --yes-playlist Download the playlist, if the URL refers to a video and a playlist. -a, --batch-file FILE File containing URLs to download ('-' for stdin.) --restrict-filenames Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames. -w, --no-overwrites Do not overwrite files. --write-description Write video description to a .description file. --write-info-json Write video metadata to a .info.json file. --write-annotations Write video annotations to a .annotations.xml file. -q, --quiet Activate quiet mode. --no-mtime Set the file last modified date/time to the download date/time. --no-warnings Ignore warnings. --console-title Display progress in console titlebar. --sleep-interval SECONDS Number of seconds to sleep before each download. -h, --help Print this help text and exit. -U, --update Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed.) --version Print program version and exit.
Использование:
Сначала перечислите доступные форматы с помощью -F
$ youtube-dl -F https://www.youtube.com/watch?v=VG1VVFfOnYQ 140 m4a audio only DASH audio 127k , m4a_dash container, aac @128k (44100Hz), 3.77MiB 141 m4a audio only DASH audio 255k , m4a_dash container, aac @256k (44100Hz), 7.57MiB *** 160 mp4 256x144 DASH video 113k , 12fps, video only, 3.24MiB 133 mp4 426x240 DASH video 269k , 24fps, video only, 7.27MiB 134 mp4 640x360 DASH video 272k , 24fps, video only, 6.55MiB 244 webm 854x480 DASH video 504k , 24fps, video only, 7.95MiB 135 mp4 854x480 DASH video 540k , 24fps, video only, 13.33MiB 136 mp4 1280x720 DASH video 1155k , 24fps, video only, 26.62MiB 248 webm 1920x1080 DASH video 1797k , 24fps, video only, 30.81MiB 137 mp4 1920x1080 DASH video 2750k , 24fps, video only, 57.97MiB *** 43 webm 640x360 18 mp4 640x360 22 mp4 1280x720 (best)
Используя коды в самом первом столбце, вы можете выбрать определенный размер видео и аудио.
Например, давайте загрузим видео с разрешением 1920x1080 (137) плюс 255K аудио (141), поэтому команда будет выглядеть так:
youtube-dl -f 137+141 https://www.youtube.com/watch?v=VG1VVFfOnYQ
Если вам просто нужно максимально возможное качество, это значение по умолчанию, поэтому все, что вам нужно, это:
youtube-dl https://www.youtube.com/watch?v=VG1VVFfOnYQ
По умолчанию дата / время загруженного файла будет равно дате / времени загрузки, чтобы отключить это и вернуть дату загрузки, используйте параметр - no-mtime.
2. БУДЬТЕ БДИТЬ
Предотвратить переход системы в спящий режим от имени утилиты.
Синтаксис:
caffeinate [-disu] [-t timeout] [-w pid] [utility arguments...] Key -d Create an assertion to prevent the display from sleeping. -i Create an assertion to prevent the system from idle sleeping. -m Create an assertion to prevent the disk from idle sleeping. -s Create an assertion to prevent the system from sleeping. This assertion is valid only when system is running on AC power. -u Create an assertion to declare that user is active. If the display is off, this option turns the display on and prevents the display from going into idle sleep. If a timeout is not specified with '-t' option, then this assertion is taken with a default of 5 second timeout. -t Specifies the timeout value in seconds for which this assertion has to be valid. The assertion is dropped after the specified timeout. Timeout value is not used when an utility is invoked with this command. -w Waits for the process with the specified pid to exit. Once the the process exits, the assertion is also released. This option is ignored when used with utility option.
Использование:
Предотвратить сон на 1 час (3600 секунд)
caffeinate -u -t 3600
Сделайте вилку caffeinate процессом, выполните в ней команду "make" и сохраните утверждение, предотвращающее бездействие, пока этот процесс выполняется:
caffeinate -i make
3. СКРИНШОТ
Сделайте снимок всего или части экрана.
Синтаксис:
screencapture [options] [file] Key -c Force screen capture to go to the clipboard. -C Capture the cursor as well as the screen. Only allowed in non-interactive modes. -d Display errors to the user graphically. -i Capture screen interactively, by selection or window. The control key = copy screen to the clipboard. The space key will toggle between mouse selection and window selection modes. The escape key will cancel the screen shot. -m Only capture the main monitor, undefined if -i is set. -M Open the taken picture in a new Mail message. -o In window capture mode, do not capture the shadow of the window. -P Open the taken picture in a Preview window. -s Only allow mouse selection mode. -S In window capture mode, capture the screen instead of the window. -t format Image format to create, default is png (other options include pdf, jpg, tiff and others). -T seconds Take the picture after a delay of seconds, default=5 Handy for arranging windows/menus before taking the screenshot. -w Only allow window selection mode. -W Start interaction in window selection mode. -x Do not play sounds. -l windowid Capture a specific windowsid. -R x,y,w,h Capture a screen rectangle, top,left,width,height. file Where to save the screen capture, 1 file per screen. -help Display brief syntax summary.
Использование:
Используйте команду ниже, чтобы сделать снимок экрана выбранной области. Мышь превратится в перекрестие, нажмите пробел для выбора режима камеры, теперь щелкните окно, на вашем рабочем столе появится файл с именем «example.png».
screencapture -i ~/Desktop/example.png
4. ТЕКСТ К РЕЧИ
Преобразуйте текст в слышимую речь.
Этот инструмент использует диспетчер синтеза речи для преобразования входящего текста в звуковую речь и либо воспроизводит его через устройство вывода звука, выбранное в Системных настройках, либо сохраняет его в файл AIFF.
Синтаксис:
say [-v voice] [-o out.aiff | -n name:port ] [-f file.in | string ...] Key string The text to speak on the command line. This can consist of multiple arguments, which are considered to be separated by spaces. --input-file=file -f file A file to be spoken. If file is - or neither this parameter nor a message is specified, read from standard input. --file-format=format The format of the file to write (AIFF, caff, m4af, WAVE). Generally, it's easier to specify a suitable file extension for the output file. To obtain a list of writable file formats, specify '?' as the format name. --data-format=format The format of the audio data to be stored. default=linear PCM. --progress Display a progress meter during synthesis. --rate=rate -r rate Speech rate to be used, in words per minute. --voice=voice -v voice The voice to be used: English language = Alex, Daniel, Fiona, Fred, Samantha or Victoria Default is the voice selected in System Preferences | Speech Other voices are available for foreign languages. --voice=? List all available voices. --output-file=fileout.aiff -o fileout.aiff An AIFF file to be written, some voices support other file formats. --channels=channels The number of channels. Most synthesizers produce mono audio only. --bit-rate=rate The bit rate for formats, default=AAC.specify '?' as the rate. --quality=quality The audio converter quality level between 0 (lowest) and 127 (highest). --network-send=name -n name --network-send=name:port -n name:port --network-send=:port -n :port --network-send=: -n : Specify a service name (default "AUNetSend") and/or IP port to be used for redirecting the speech output through AUNetSend. specify '?' as the device name to obtain a list of audio output devices.
Использование:
say -f myfile.txt cat myfile.txt | say
5. НАСТРОЙКА СИСТЕМЫ
Настройте определенные параметры для каждой машины, которые обычно настраиваются в приложении «Системные настройки».
Синтаксис:
sudo systemsetup
Для запуска команды systemsetup требуются как минимум права администратора.
Использование:
sudo systemsetup -getcomputername sudo systemsetup -setdate 12:31:17 Key: [-getdate] [-setdate mm:dd:yy] [-gettime] [-settime hh:mm:ss] [-gettimezone] [-listtimezones] [-settimezone timezone] [-getusingnetworktime] [-setusingnetworktime on | off] [-getnetworktimeserver] [-setnetworktimeserver timeserver] [-getsleep] [-setsleep minutes] [-getcomputersleep] [-setcomputersleep minutes] [-getdisplaysleep] [-setdisplaysleep minutes] [-getharddisksleep] [-setharddisksleep minutes] [-getwakeonmodem] [-setwakeonmodem on | off] [-getwakeonnetworkaccess] [-setwakeonnetworkaccess on | off] [-getrestartpowerfailure] [-setrestartpowerfailure on | off] [-getrestartfreeze] [-setrestartfreeze on | off] [-getallowpowerbuttontosleepcomputer] [-setallowpowerbuttontosleepcomputer on | off] [-getremotelogin] [-setremotelogin on | off] [-getremoteappleevents] [-setremoteappleevents on | off] [-getcomputername] [-setcomputername computername] [-getstartupdisk] [-liststartupdisks] [-setstartupdisk path] [-getwaitforstartupafterpowerfailure] [-setwaitforstartupafterpowerfailure value] [-getdisablekeyboardwhenenclosurelockisengaged] [-setdisablekeyboardwhenenclosurelockisengaged yes | no] [-getkernelbootarchitecturesetting] [-setkernelbootarchitecture i386 | x86_64 | default] [-version] [-help] [-printCommands]