Linux остановить скрипт python

How to kill python script with bash script

I try to check the running processes by ps aux | less and found that the running script having command of python test.py Please assist, thank you!

5 Answers 5

(or) a more fool-proof way using pgrep to search for the actual process-id

kill $(pgrep -f 'python test.py') 

Or if more than one instance of the running program is identified and all of them needs to be killed, use killall(1) on Linux and BSD

works like a champ for multiple python processes in the background in linux. I’ve never used pkill but it’s certainly easier than kill or killall. nice

You can use the ! to get the PID of the last command.

I would suggest something similar to the following, that also check if the process you want to run is already running:

#!/bin/bash if [[ ! -e /tmp/test.py.pid ]]; then # Check if the file already exists python test.py & #+and if so do not run another process. echo $! > /tmp/test.py.pid else echo -n "ERROR: The process is already running with pid " cat /tmp/test.py.pid echo fi 

Then, when you want to kill it:

#!/bin/bash if [[ -e /tmp/test.py.pid ]]; then # If the file do not exists, then the kill `cat /tmp/test.py.pid` #+the process is not running. Useless rm /tmp/test.py.pid #+trying to kill it. else echo "test.py is not running" fi 

Of course if the killing must take place some time after the command has been launched, you can put everything in the same script:

#!/bin/bash python test.py & # This does not check if the command echo $! > /tmp/test.py.pid #+has already been executed. But, #+would have problems if more than 1 sleep() #+have been started since the pid file would. #+be overwritten. if [[ -e /tmp/test.py.pid ]]; then kill `cat /tmp/test.py.pid` else echo "test.py is not running" fi 

If you want to be able to run more command with the same name simultaneously and be able to kill them selectively, a small edit of the script is needed. Tell me, I will try to help you!

With something like this you are sure you are killing what you want to kill. Commands like pkill or grepping the ps aux can be risky.

Источник

Как вручную остановить скрипт Python, который работает непрерывно в linux

У меня есть скрипт Python, который работает и постоянно сбрасывает ошибки в файл журнала.

Я хочу, чтобы отредактировать скрипт и запустить его снова, но не знаю, как остановить скрипт.

Я в настоящее время вошел в Linux через PuTTy и делаю все кодирование там. Итак, есть ли команда для остановки скрипта python в linux?

Количество просмотров материала

26.02.2023 4:18 2704

Распечатать страницу

6 ответов

вам нужно будет найти идентификатор процесса (pid). одна команда, чтобы сделать это будет

чтобы ограничить результаты процессов python вы можете grep результат

Читайте также:  What is pcmcia in linux

который даст результаты, такие как:

user 2430 1 0 Jul03 ? 00:00:01 /usr/bin/python -tt /usr/sbin/yum-updatesd 

второй столбец-pid. затем используйте команду kill как таковую:

$> kill -9 2430 (i.e. the pid returned) 

найти идентификатор процесса (PID) сценария и выдать kill -9 PID чтобы убить процесс, если он не работает как ваш процесс forground на терминале, и в этом случае вы можете Contrl-C, чтобы убить его.

найдите PID с помощью следующей команды:

список процессов Python, выбрать один правильный и отметить его PID. Тогда

убить процесс. Вы можете получить сообщение о завершении процесса на этом этап.

в качестве альтернативы, вы можете использовать top команда для поиска процесса python. Просто введите k (для убийства) и top программа предложит вам для PID процесса, чтобы убить. Иногда трудно увидеть все процессы, которые вас интересуют top так как они могут прокручивать экран, я думаю, что ps подход проще / лучше.

Если программа является текущим процессом в вашей оболочке, ввод Ctrl-C остановит программу Python.

попробуйте эту простую строку, она завершит все script.py :

в идеальном мире вы бы прочитали документацию к скрипту и увидели, какой сигнал(ы) следует использовать, чтобы сообщить ему о завершении. В реальной жизни вы, вероятно, захотите отправить ему сигнал термина, во-первых, возможно, используя сигнал убийства, если он игнорирует термин. Итак, что вы делаете, это найти идентификатор процесса, используя команду ps (как кто-то уже описал). Тогда, вы можете запустить kill -TERM . Некоторые программы будут убирать вещи, например, файлы, которые они могут открыть, когда они получают такой сигнал, поэтому лучше начать с чем-то подобным. Если это не удастся, то не так много осталось сделать, кроме большого молотка: kill -KILL . (вы можете использовать числовые значения, например-KILL = -9, и они, вероятно, никогда не изменятся, но в теоретическом смысле может быть безопаснее использовать имена)

Если вы знаете имя скрипта, вы можете свести всю работу к одной команде:

ps -ef | grep "script_name" | awk '' | xargs sudo kill 

Если вы хотите убедиться, что это скрипт python:

ps -ef | grep "python script_name" | awk '' | xargs sudo kill 

Если вы хотите, чтобы убить все скрипты python:

ps -ef | grep "python" | awk '' | xargs sudo kill 

напоминание: вы должны процитировать «» имя сценария, как в примерах.

Постоянная ссылка на данную страницу: [ Скопировать ссылку | Сгенерировать QR-код ]

Ваш ответ

Опубликуйте как Гость или авторизуйтесь

Похожие вопросы про тегам:

  • 7 Какое максимальное количество разделов можно создать на жестком диске?
  • 3 Таблица прилипает к верхней части страницы, как ее удалить?
  • 6 При двусторонней печати как исправить, что задняя страница печатается вверх ногами?
  • 4 Как превратить оглавление в простой форматированный текст?
  • 5 Что значит 1Rx8 и 2Rx8 для оперативной памяти и совместимы ли они?
  • 10 Копирование и вставка в Windows PowerShell
  • 13 Сочетание клавиш для сворачивания удаленного рабочего стола
  • 1 Как включить фон рабочего стола на удаленном компьютере?
  • 5 Как сделать ярлык на рабочем столе доступным для всех пользователей в Windows 10
  • 1 Зачем Windows 10 нужна служба очереди сообщений и почему она установлена по умолчанию?
  • Наушники Wireless и True Wireless: чем они отличаются?
  • Не включается iPad: причины и решения проблемы
  • Как ускорить передачу данных по Bluetooth
  • Как правильно приобрести подержанный iPhone?
  • Каковы преимущества фотоэлектрической системы?
  • 5 лучших USB–пылесосов для клавиатуры
  • Как выбрать чехол-аккумулятор для смартфона
  • Мобильный телефон Razr: новая складная раскладушка от Motorola стоит 1200 евро
  • Компания Nothing: смартфон Phone 2 должен быть «более премиальным» и выйти в этом году
  • UMTS — История технологии сотовой связи
  • Выбор домена
  • 3D-печать: будущее массового производства
  • Искусственный интеллект в малом бизнесе: как улучшить эффективность и конкурентоспособность
  • Ошибки, которых стоит избегать при продвижении сайта
  • Высокие технологии в Windows: что это такое и как их использовать в своих приложениях
  • Сдать квартиру в Москве безопасно и выгодно − это вполне реально
  • Зарабатывай на ненужных скинах CS:GO
Читайте также:  What is sudo bash in linux
Apple $173,24 +0,81%
Amazon $114,49 -1,94%
Microsoft $325,19 +3,61%
Google $123,44 +2,11%
Netflix $364,74 -0,03%
Intel $27,45 -5,34%
Facebook $254,49 +2,11%
Tesla $185,54 +1,44%
Tencent $322,40 -3,01%

Все дело в мыслях. Мысль — начало всего. И мыслями можно управлять. И поэтому главное дело совершенствования: работать над мыслями.

Источник

Kill python interpeter in linux from the terminal

I want to kill python interpeter — The intention is that all the python files that are running in this moment will stop (without any informantion about this files). obviously the processes should be closed. Any idea as delete files in python or destroy the interpeter is ok 😀 (I am working with virtual machine). I need it from the terminal because i write c code and i use linux commands. Hope for help

9 Answers 9

should kill any running python process.

-9 sets the signal to SIGKILL Others include: SIGHUP -1 Hangup. SIGINT -2 Interrupt from keyboard. SIGKILL -9 Kill signal. SIGTERM -15 Termination signal. SIGSTOP -17, -19, -23 Stop the process.

There’s a rather crude way of doing this, but be careful because first, this relies on python interpreter process identifying themselves as python, and second, it has the concomitant effect of also killing any other processes identified by that name.

In short, you can kill all python interpreters by typing this into your shell (make sure you read the caveats above!):

ps aux | grep python | grep -v "grep python" | awk '' | xargs kill -9 

To break this down, this is how it works. The first bit, ps aux | grep python | grep -v «grep python» , gets the list of all processes calling themselves python, with the grep -v making sure that the grep command you just ran isn’t also included in the output. Next, we use awk to get the second column of the output, which has the process ID’s. Finally, these processes are all (rather unceremoniously) killed by supplying each of them with kill -9 .

Источник

How to manually stop a Python script that runs continuously on linux

I have a Python script that is running and continuously dumping errors into a log file. I want to edit the script and run it again, but don’t know how to stop the script. I’m currently logged on Linux through PuTTy and am doing all the coding there. So, is there a command to stop the python script in linux?

7 Answers 7

You will have to find the process id (pid). one command to do this would be

Читайте также:  Zynq linux on qspi flash

to limit results to python processes you can grep the result

which will give results like :

user 2430 1 0 Jul03 ? 00:00:01 /usr/bin/python -tt /usr/sbin/yum-updatesd 

the second column is the pid. then use the kill command as such :

$> kill -9 2430 (i.e. the pid returned) 

Try this simple line, It will terminate all script.py :

Find the process id (PID) of the script and issue a kill -9 PID to kill the process unless it’s running as your forground process at the terminal in which case you can Contrl-C to kill it.

Find the PID with this command:

It lists all the python processes, pick out the right one and note its PID. Then

will kill the process. You may get a message about having terminated a process at this stage.

Alternatively, you can use the top command to find the python process. Simply enter k (for kill) and the top program will prompt you for the PID of the process to kill. Sometimes it’s difficult to see all processes you are interested in with top since they may scroll off the screen, I think the ps approach is easier/better.

If the program is the current process in your shell, typing Ctrl-C will stop the Python program.

If you are running a process in a loop it will only kill that process rather than the python script. For example, I have a python script to read URLs from a file, and for each URL it will run youtube-dl to download the video. If I press Ctrl + C it will only kill the youtube-dl process. Then it will move on to the next item.

In a perfect world, you’d read the documentation for the script and see which signal(s) should be used to tell it to end. In real life, you probably want to send it the TERM signal, first, maybe using a KILL signal if it ignores the TERM. So, what you do is find the Process ID, using the ps command (as someone already described). Then, you can run kill -TERM . Some programs will clean up things, like files they might have open, when they get a signal like that, so it’s nicer to start with something like that. If that fails, then there’s not much left to do except the big hammer: kill -KILL . (you can use the numeric values, e.g. -KILL = -9, and they’ll probably never change, but in a theoretical sense it might be safer to use the names)

If you know the name of the script you could reduce all the work to a single command:

ps -ef | grep "script_name" | awk '' | xargs sudo kill 

If you want to make sure that is a python script:

ps -ef | grep "python script_name" | awk '' | xargs sudo kill 

If you wanted to kill all the python scripts:

ps -ef | grep "python" | awk '' | xargs sudo kill 

I suppose you get the idea 😉

Reminder: you need to quote «» the script name as is in the examples.

Источник

Оцените статью
Adblock
detector