标签归档:termination

如何停止/终止python脚本的运行?

问题:如何停止/终止python脚本的运行?

我用IDLE编写了一个程序来标记文本文件,然后开始标记349个文本文件!我该如何阻止它?如何停止正在运行的Python程序?

I wrote a program in IDLE to tokenize text files and it starts to tokeniza 349 text files! How can I stop it? How can I stop a running Python program?


回答 0

要停止程序,只需按Control + C

To stop your program, just press Control + C.


回答 1

如果exit()在代码中使用该函数,也可以执行此操作。更理想的是,您可以这样做sys.exit()。即使您通过软件包并行运行程序sys.exit()也可能终止Python multiprocessing

注意:为了使用sys.exit(),您必须将其导入:import sys

You can also do it if you use the exit() function in your code. More ideally, you can do sys.exit(). sys.exit() which might terminate Python even if you are running things in parallel through the multiprocessing package.

Note: In order to use the sys.exit(), you must import it: import sys


回答 2

如果您的程序在交互式控制台上运行,则按CTRL+CKeyboardInterrupt在主线程上引发异常。

如果您的Python程序没有捕获到它,KeyboardInterrupt则会导致Python退出。但是,一个except KeyboardInterrupt:块或类似裸露的东西except:将阻止此机制实际停止脚本的运行。

有时,如果KeyboardInterrupt无法正常工作,您可以发送SIGBREAK信号。在Windows上,解释器可以处理CTRL+Pause/Break而不生成可捕获的KeyboardInterrupt异常。

但是,这些机制主要仅在Python解释器正在运行并响应操作系统事件时才起作用。如果Python解释器由于某种原因没有响应,则最有效的方法是终止运行解释器的整个操作系统进程。其机制因操作系统而异。

在Unix风格的shell环境,您可以按CTRL+Z中止任何进程当前控制的控制台。返回shell提示后,您可以使用jobs它列出挂起的作业,并可以使用杀死第一个挂起的作业kill %1。(如果要重新开始运行,可以使用fg %1;在前台继续执行作业;有关更多信息,请阅读Shell的作业控制手册。)

另外,在Unix或类似Unix的环境中,您可以找到Python进程的PID(进程标识符)并用PID杀死它。使用类似的方法ps aux | grep python来查找正在运行的Python进程,然后使用kill <pid>发送SIGTERM信号。

killUnix上的命令SIGTERM默认发送,Python程序可以安装信号处理程序以SIGTERM使用该signal模块。从理论上讲,任何用于的信号处理程序SIGTERM都应正常关闭进程。但是有时,如果进程卡住了(例如,在不间断的IO睡眠状态下被阻塞),则SIGTERM信号无效,因为该进程甚至无法唤醒以处理该信号。

为了强行终止不响应信号的进程,您需要发送SIGKILL信号,有时称为,kill -9因为它9SIGKILL常量的数值。在命令行中,您可以使用kill -KILL <pid>(或kill -9 <pid>简称)发送aSIGKILL并立即停止该进程运行。

在Windows上,您没有Unix的进程信号系统,但是您可以使用TerminateProcess函数强制终止正在运行的进程。以交互方式,最简单的方法是打开任务管理器,找到python.exe与您的程序相对应的进程,然后单击“结束进程”按钮。您也可以将taskkill命令用于类似目的。

If your program is running at an interactive console, pressing CTRL + C will raise a KeyboardInterrupt exception on the main thread.

If your Python program doesn’t catch it, the KeyboardInterrupt will cause Python to exit. However, an except KeyboardInterrupt: block, or something like a bare except:, will prevent this mechanism from actually stopping the script from running.

Sometimes if KeyboardInterrupt is not working you can send a SIGBREAK signal instead; on Windows, CTRL + Pause/Break may be handled by the interpreter without generating a catchable KeyboardInterrupt exception.

However, these mechanisms mainly only work if the Python interpreter is running and responding to operating system events. If the Python interpreter is not responding for some reason, the most effective way is to terminate the entire operating system process that is running the interpreter. The mechanism for this varies by operating system.

In a Unix-style shell environment, you can press CTRL + Z to suspend whatever process is currently controlling the console. Once you get the shell prompt back, you can use jobs to list suspended jobs, and you can kill the first suspended job with kill %1. (If you want to start it running again, you can continue the job in the foreground by using fg %1; read your shell’s manual on job control for more information.)

Alternatively, in a Unix or Unix-like environment, you can find the Python process’s PID (process identifier) and kill it by PID. Use something like ps aux | grep python to find which Python processes are running, and then use kill <pid> to send a SIGTERM signal.

The kill command on Unix sends SIGTERM by default, and a Python program can install a signal handler for SIGTERM using the signal module. In theory, any signal handler for SIGTERM should shut down the process gracefully. But sometimes if the process is stuck (for example, blocked in an uninterruptable IO sleep state), a SIGTERM signal has no effect because the process can’t even wake up to handle it.

To forcibly kill a process that isn’t responding to signals, you need to send the SIGKILL signal, sometimes referred to as kill -9 because 9 is the numeric value of the SIGKILL constant. From the command line, you can use kill -KILL <pid> (or kill -9 <pid> for short) to send a SIGKILL and stop the process running immediately.

On Windows, you don’t have the Unix system of process signals, but you can forcibly terminate a running process by using the TerminateProcess function. Interactively, the easiest way to do this is to open Task Manager, find the python.exe process that corresponds to your program, and click the “End Process” button. You can also use the taskkill command for similar purposes.


回答 3

  • 要停止python脚本,只需按Ctrl + C
  • 在脚本中exit(),您可以执行此操作。
  • 您可以在退出后的交互式脚本中进行操作。
  • 您可以使用pkill -f name-of-the-python-script
  • To stop a python script just press Ctrl + C.
  • Inside a script with exit(), you can do it.
  • You can do it in an interactive script with just exit.
  • You can use pkill -f name-of-the-python-script.

回答 4

Ctrl-BreakCtrl-C更强大

Ctrl-Break it is more powerful than Ctrl-C


回答 5

要停止正在运行的程序,请使用Ctrl+C终止该过程。

要在python中以编程方式处理它,请导入sys模块并sys.exit()在要终止程序的位置使用。

import sys
sys.exit()

To stop a running program, use Ctrl+C to terminate the process.

To handle it programmatically in python, import the sys module and use sys.exit() where you want to terminate the program.

import sys
sys.exit()

回答 6

要使用键盘停止python脚本,请执行以下操作:Ctrl+C

使用代码停止它(这在Python 3上对我有用):

import os
os._exit(0)

您还可以使用:

import sys
sys.exit()

要么:

exit()

要么:

raise SystemExit

To stop a python script using the keyboard: Ctrl + C

To stop it using code (This has worked for me on Python 3) :

import os
os._exit(0)

you can also use:

import sys
sys.exit()

or:

exit()

or:

raise SystemExit

回答 7

如果您陷入python shell中,请按Ctrl +Z。请记住,脚本实例可以在后台继续运行,因此在Linux下,您必须终止相应的进程。

Ctrl + Z should do it, if you’re caught in the python shell. Keep in mind that instances of the script could continue running in background, so under linux you have to kill the corresponding process.


回答 8

当我在Linux终端上运行python脚本时,CTRL + \起作用。(不是CRTL + C或D)

When I have a python script running on a linux terminal, CTRL + \ works. (not CRTL + C or D)


回答 9

Control+D在Windows 10上对我有效。此外,放在exit()末尾也适用。

Control+D works for me on Windows 10. Also, putting exit() at the end also works.


回答 10

如果您在Jupyter Notebook中,则exit()会杀死内核,所以这不是一个好主意。raise命令将停止程序。

exit() will kill the Kernel if you’re in Jupyter Notebook so it’s not a good idea. raise command will stop the program.


回答 11

您还可以使用Activity Monitor停止py进程

you can also use the Activity Monitor to stop the py process


回答 12

要停止程序,只需按CTRL+D

exit()

To stop your program, just press CTRL + D

or exit().


回答 13

Ctrl+ Alt+ Delete,将弹出任务管理器。找到正在运行的Python命令,右键单击它,然后单击“停止”或“杀死”。

Press Ctrl+Alt+Delete and Task Manager will pop up. Find the Python command running, right click on it and and click Stop or Kill.


回答 14

如果您正在使用Spyder,请使用CTRL +。 (DOT),您将重新启动内核,也将停止程序。

If you are working with Spyder, use CTRL + . (DOT) and you will restart the kernel, also you will stop the program.


回答 15

Windows解决方案:Control + C

Macbook解决方案:Control (^) + C

另一种方法是打开一个终端,键入top,记下PID您想杀死的进程,然后在终端上键入:kill -9 <pid>

Windows solution: Control + C.

Macbook solution: Control (^) + C.

Another way is to open a terminal, type top, write down the PID of the process that you would like to kill and then type on the terminal: kill -9 <pid>


如何终止Python脚本

问题:如何终止Python脚本

我知道die()PHP 中的命令会较早退出脚本。

如何在Python中执行此操作?

I am aware of the die() command in PHP which exits a script early.

How can I do this in Python?


回答 0

import sys
sys.exit()

sys模块文档中的详细信息:

sys.exit([arg])

从Python退出。这是通过引发SystemExit异常来实现的,因此可以执行 try语句的finally子句指定的清除操作,并且有可能在外部级别拦截出口尝试。

可选参数arg可以是给出退出状态的整数(默认为零),也可以是其他类型的对象。如果它是整数,则Shell等将零视为“成功终止”,而将任何非零值视为“异常终止”。大多数系统要求它的范围是0-127,否则会产生不确定的结果。某些系统具有为特定的退出代码分配特定含义的约定,但是这些通常不完善。Unix程序通常将2用于命令行语法错误,将1用于所有其他类型的错误。如果传递了另一种类型的对象,则“无”等效于传递零,并且将任何其他对象输出stderr并导致退出代码为1。特别是, sys.exit("some error message") 是发生错误时退出程序的快速方法。

由于exit()最终“仅”会引发异常,因此它仅在从主线程调用时才退出进程,并且不会拦截该异常。

请注意,这是退出的“不错”方式。下面的@ glyphtwistedmatrix指出,如果您想要“硬出口”,则可以使用os._exit(*errorcode*),尽管它在某种程度上可能是特定于OS的(例如,在Windows下可能不会显示错误代码),并且它肯定不那么友好,因为它在进程终止之前,不允许解释器进行任何清理。

import sys
sys.exit()

details from the sys module documentation:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Note that this is the ‘nice’ way to exit. @glyphtwistedmatrix below points out that if you want a ‘hard exit’, you can use os._exit(*errorcode*), though it’s likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn’t let the interpreter do any cleanup before the process dies.


回答 1

一种提前终止Python脚本的简单方法是使用内置quit()函数。无需导入任何库,它既高效又简单。

例:

#do stuff
if this == that:
  quit()

A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

Example:

#do stuff
if this == that:
  quit()

回答 2

另一种方法是:

raise SystemExit

Another way is:

raise SystemExit

回答 3

您也可以简单地使用exit()

请记住sys.exit()exit()quit(),和os._exit(0) Python解释器。因此,如果它出现在由另一个脚本通过调用的脚本中execfile(),它将停止两个脚本的执行。

请参阅“ 停止执行用execfile调用的脚本 ”来避免这种情况。

You can also use simply exit().

Keep in mind that sys.exit(), exit(), quit(), and os._exit(0) kill the Python interpreter. Therefore, if it appears in a script called from another script by execfile(), it stops execution of both scripts.

See “Stop execution of a script called with execfile” to avoid this.


回答 4

尽管您通常应该选择sys.exit它是因为它比其他代码更“友好”,但它实际上所做的只是引发一个异常。

如果您确定需要立即退出进程,并且您可能在某个将捕获的异常处理程序中SystemExit,则可以使用另一个函数– os._exit在C级别立即终止,并且不执行任何正常的删除操作口译员 例如,不执行在“ atexit”模块中注册的钩子。

While you should generally prefer sys.exit because it is more “friendly” to other code, all it actually does is raise an exception.

If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch SystemExit, there is another function – os._exit – which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the “atexit” module are not executed.


回答 5

我刚刚发现了写multithreadded的应用程序时,raise SystemExitsys.exit()两个只有杀死正在运行的线程。另一方面,os._exit()退出整个过程。在“ 为什么在Python的线程内调用sys.exit()不会退出?中对此进行了讨论。

下面的示例有2个线程。肯尼和卡特曼。卡特曼本应该永远活着,但肯尼却被递归召唤,应该在3秒后死亡。(递归调用不是最好的方法,但是我还有其他原因)

如果我们还希望卡特曼在肯尼死后去世,那么肯尼就应该离开os._exit,否则,只有肯尼会死,卡特曼才能永远生活。

import threading
import time
import sys
import os

def kenny(num=0):
    if num > 3:
        # print("Kenny dies now...")
        # raise SystemExit #Kenny will die, but Cartman will live forever
        # sys.exit(1) #Same as above

        print("Kenny dies and also kills Cartman!")
        os._exit(1)
    while True:
        print("Kenny lives: {0}".format(num))
        time.sleep(1)
        num += 1
        kenny(num)

def cartman():
    i = 0
    while True:
        print("Cartman lives: {0}".format(i))
        i += 1
        time.sleep(1)

if __name__ == '__main__':
    daemon_kenny = threading.Thread(name='kenny', target=kenny)
    daemon_cartman = threading.Thread(name='cartman', target=cartman)
    daemon_kenny.setDaemon(True)
    daemon_cartman.setDaemon(True)

    daemon_kenny.start()
    daemon_cartman.start()
    daemon_kenny.join()
    daemon_cartman.join()

I’ve just found out that when writing a multithreadded app, raise SystemExit and sys.exit() both kills only the running thread. On the other hand, os._exit() exits the whole process. This was discussed in “Why does sys.exit() not exit when called inside a thread in Python?“.

The example below has 2 threads. Kenny and Cartman. Cartman is supposed to live forever, but Kenny is called recursively and should die after 3 seconds. (recursive calling is not the best way, but I had other reasons)

If we also want Cartman to die when Kenny dies, Kenny should go away with os._exit, otherwise, only Kenny will die and Cartman will live forever.

import threading
import time
import sys
import os

def kenny(num=0):
    if num > 3:
        # print("Kenny dies now...")
        # raise SystemExit #Kenny will die, but Cartman will live forever
        # sys.exit(1) #Same as above

        print("Kenny dies and also kills Cartman!")
        os._exit(1)
    while True:
        print("Kenny lives: {0}".format(num))
        time.sleep(1)
        num += 1
        kenny(num)

def cartman():
    i = 0
    while True:
        print("Cartman lives: {0}".format(i))
        i += 1
        time.sleep(1)

if __name__ == '__main__':
    daemon_kenny = threading.Thread(name='kenny', target=kenny)
    daemon_cartman = threading.Thread(name='cartman', target=cartman)
    daemon_kenny.setDaemon(True)
    daemon_cartman.setDaemon(True)

    daemon_kenny.start()
    daemon_cartman.start()
    daemon_kenny.join()
    daemon_cartman.join()

回答 6

from sys import exit
exit()

作为参数,您可以传递退出代码,该退出代码将返回给OS。默认值为0。

from sys import exit
exit()

As a parameter you can pass an exit code, which will be returned to OS. Default is 0.


回答 7

我是一个新手,但可以肯定的是,它更干净,更易控制

def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        return
    print 'You wont see this'

if __name__ == '__main__': 
    main()

程序终止

import sys
def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        sys.exit()
    print 'You wont see this'

if __name__ == '__main__': 
    main()

程序终止了回溯(最近一次调用最后一次):main()中的文件“ Z:\ Directory \ testdieprogram.py”,第12行,sys.exit中主要的文件“ Z:\ Directory \ testdieprogram.py”,第8行( )SystemExit

编辑

关键是该程序可以顺利,和平地结束,而不是“我已停止!!!!”

I’m a total novice but surely this is cleaner and more controlled

def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        return
    print 'You wont see this'

if __name__ == '__main__': 
    main()

Program terminated

than

import sys
def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        sys.exit()
    print 'You wont see this'

if __name__ == '__main__': 
    main()

Program terminated Traceback (most recent call last): File “Z:\Directory\testdieprogram.py”, line 12, in main() File “Z:\Directory\testdieprogram.py”, line 8, in main sys.exit() SystemExit

Edit

The point being that the program ends smoothly and peacefully, rather than “I’VE STOPPED !!!!”


回答 8

在Python 3.5中,我尝试合并类似的代码,而不使用内置的模块(例如sys,Biopy)来停止脚本并向用户打印错误消息。这是我的示例:

## My example:
if "ATG" in my_DNA: 
    ## <Do something & proceed...>
else: 
    print("Start codon is missing! Check your DNA sequence!")
    exit() ## as most folks said above

后来,我发现抛出一个错误更为简洁:

## My example revised:
if "ATG" in my_DNA: 
    ## <Do something & proceed...>
else: 
    raise ValueError("Start codon is missing! Check your DNA sequence!")

In Python 3.5, I tried to incorporate similar code without use of modules (e.g. sys, Biopy) other than what’s built-in to stop the script and print an error message to my users. Here’s my example:

## My example:
if "ATG" in my_DNA: 
    ## <Do something & proceed...>
else: 
    print("Start codon is missing! Check your DNA sequence!")
    exit() ## as most folks said above

Later on, I found it is more succinct to just throw an error:

## My example revised:
if "ATG" in my_DNA: 
    ## <Do something & proceed...>
else: 
    raise ValueError("Start codon is missing! Check your DNA sequence!")

回答 9

我的两分钱。

Python 3.8.1,Windows 10、64位。

sys.exit() 无法直接为我工作。

我有几个下一个循环。

首先,我声明一个布尔变量,称为immediateExit

因此,在程序代码的开头,我写了:

immediateExit = False

然后,从最内部的(嵌套的)循环异常开始,我写:

            immediateExit = True
            sys.exit('CSV file corrupted 0.')

然后,我进入外循环的直接延续,在代码执行任何其他操作之前,我写了:

    if immediateExit:
        sys.exit('CSV file corrupted 1.')

根据复杂程度,有时除部分内容外,还需要重复上述说明。

    if immediateExit:
        sys.exit('CSV file corrupted 1.5.')

自定义消息也用于我的个人调试,因为数字是出于相同的目的-查看脚本真正的退出位置。

'CSV file corrupted 1.5.'

在我的特殊情况下,我正在处理一个CSV文件,如果该软件检测到它已损坏,则我不希望该软件接触它。因此对我来说,在检测到可能的损坏后立即退出整个Python脚本非常重要。

从所有循环中逐步退出系统,我设法做到了。

完整代码:(需要进行一些更改,因为它是内部任务的专有代码):

immediateExit = False
start_date = '1994.01.01'
end_date = '1994.01.04'
resumedDate = end_date


end_date_in_working_days = False
while not end_date_in_working_days:
    try:
        end_day_position = working_days.index(end_date)

        end_date_in_working_days = True
    except ValueError: # try statement from end_date in workdays check
        print(current_date_and_time())
        end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
        print('New end date: ', end_date, '\n')
        continue


    csv_filename = 'test.csv'
    csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
    try:
        with open(csv_filename, 'r') as file:
            print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
            last_line = file.readlines()[-1]
            start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
            resumedDate = start_date

            if last_line == csv_headers:
                pass
            elif start_date not in working_days:
                print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
                immediateExit = True
                sys.exit('CSV file corrupted 0.')
            else:
                start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
                print('\nLast date:', start_date)
                file.seek(0) # setting the cursor at the beginnning of the file
                lines = file.readlines() # reading the file contents into a list
                count = 0 # nr. of lines with last date
                for line in lines: #cycling through the lines of the file
                    if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
                        count = count + 1
        if immediateExit:
            sys.exit('CSV file corrupted 1.')
        for iter in range(count): # removing the lines with last date
            lines.pop()
        print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))



        if immediateExit:
            sys.exit('CSV file corrupted 1.2.')
        with open(csv_filename, 'w') as file:
            print('\nFile', csv_filename, 'open for writing')
            file.writelines(lines)

            print('\nRemoving', count, 'lines from', csv_filename)

        fileExists = True

    except:
        if immediateExit:
            sys.exit('CSV file corrupted 1.5.')
        with open(csv_filename, 'w') as file:
            file.write(csv_headers)
            fileExists = False
    if immediateExit:
        sys.exit('CSV file corrupted 2.')

My two cents.

Python 3.8.1, Windows 10, 64-bit.

sys.exit() does not work directly for me.

I have several nexted loops.

First I declare a boolean variable, which I call immediateExit.

So, in the beginning of the program code I write:

immediateExit = False

Then, starting from the most inner (nested) loop exception, I write:

            immediateExit = True
            sys.exit('CSV file corrupted 0.')

Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:

    if immediateExit:
        sys.exit('CSV file corrupted 1.')

Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.

    if immediateExit:
        sys.exit('CSV file corrupted 1.5.')

The custom message is for my personal debugging, as well, as the numbers are for the same purpose – to see where the script really exits.

'CSV file corrupted 1.5.'

In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.

And following the gradual sys.exit-ing from all the loops I manage to do it.

Full code: (some changes were needed because it is proprietory code for internal tasks):

immediateExit = False
start_date = '1994.01.01'
end_date = '1994.01.04'
resumedDate = end_date


end_date_in_working_days = False
while not end_date_in_working_days:
    try:
        end_day_position = working_days.index(end_date)

        end_date_in_working_days = True
    except ValueError: # try statement from end_date in workdays check
        print(current_date_and_time())
        end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
        print('New end date: ', end_date, '\n')
        continue


    csv_filename = 'test.csv'
    csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
    try:
        with open(csv_filename, 'r') as file:
            print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
            last_line = file.readlines()[-1]
            start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
            resumedDate = start_date

            if last_line == csv_headers:
                pass
            elif start_date not in working_days:
                print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
                immediateExit = True
                sys.exit('CSV file corrupted 0.')
            else:
                start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
                print('\nLast date:', start_date)
                file.seek(0) # setting the cursor at the beginnning of the file
                lines = file.readlines() # reading the file contents into a list
                count = 0 # nr. of lines with last date
                for line in lines: #cycling through the lines of the file
                    if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
                        count = count + 1
        if immediateExit:
            sys.exit('CSV file corrupted 1.')
        for iter in range(count): # removing the lines with last date
            lines.pop()
        print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))



        if immediateExit:
            sys.exit('CSV file corrupted 1.2.')
        with open(csv_filename, 'w') as file:
            print('\nFile', csv_filename, 'open for writing')
            file.writelines(lines)

            print('\nRemoving', count, 'lines from', csv_filename)

        fileExists = True

    except:
        if immediateExit:
            sys.exit('CSV file corrupted 1.5.')
        with open(csv_filename, 'w') as file:
            file.write(csv_headers)
            fileExists = False
    if immediateExit:
        sys.exit('CSV file corrupted 2.')