Restart script when error happens and continue with right line in csv file

trycatch r
r catch error and continue
error handling in r
withcallinghandlers
r try skip error
r trycatch continue
r try vs trycatch
continue package execution after error in ssis

hi guys its my first time to ask help here i hope you can help me i have this code that i write it

def my_function():
try :
    with open('file.csv', 'r') as f:
        data = list(csv.reader(f, delimiter=','))

        i = 1
        while i <= 10:
            i += 1
            fname = data[i][0]
            lname = data[i][1]

            options = Options()
            driver = webdriver.Chrome(options=options)
            driver.get("https://www.test.net/")


            #Do staff


except Exception as e:
    print(e)
    driver.quit()
    time.sleep(1)
    print('******RESTART******')
    my_function()


my_function()

well i'm trying to make this script run without stop .. the problem that i'm facing is when it stops for example in line number 8 (i = 8) and restart again ,it starts from first line (i = 1) . i want the script to restart from line 8 and continue to 9 , 10 ...

can you please guide me to the right solution .. thank you

Your code is making this far more difficult than it needs to be.

First, you almost certainly don't want to wrap this entire block of code in a "catch all" exception handler. You want your exception handling to be sufficiently specific (limited) that you can do something meaningful with the exception. For example:

#!python
# Assumes Python version 3 or later
import sys, csv

filename='myfile.csv'
with open(filename as f:
    try:
        reader = csv.reader(f)
    for record in reader:
        if len(record) != 2:
            # log error and continue
            print('Malformed records in {}: {}'.format(filename, reader.line_num), file=sys.stderr)
            continue
         # do stuff with this record, knowing it has exactly two fields:
         fname = record[0]
         lname = record[1]
         # etc ...
    except csv.Error as e:
        print('Error handling {} at line {}: {}'.format(filename, reader.line_num, e), file=sys.stderr)

Note that your errors probably weren't specifically in the csv module. It's pretty tolerant of malformed lines. But I'm showing how to wrap the reader and processing code within exception handling just for that. Your error was probably an IndexError (trying to access an item past the number of items in a list ... outside of its valid indexing range. It's better to just check the length of each record rather than use exception handling for that ... though it's possible either way.

There's a quite reasonable example (very similar code) in the documentation for the standard libraries: https://docs.python.org/3/library/csv.html

Also, stylistically, I'd suggest that a named tuple or a lightweight class (using __slots__) for managing these records. This would allow you to use dot notation to access the .fname and .lname of each rather than using [x] and numeric indexing. (Numeric indexing gets progressively more cumbersome and error prone as your code complexity increases).

Exceptions and debugging · Advanced R., What happens when something goes wrong with your R code? Errors are used when there is no way for a function to continue. Beyond Exception Handling: Conditions and Restarts by Peter Seibel. message stored in the error condition object, the following function wraps read.csv() to add the file name to any errors:. I have a file called as 'readfile.csv' with following contents. Name Id VAl Number IP James,007,$500,111-111-111,111-000-000 Bond,700,$900,100-000-999, 666-999-000 Here Name, Id, Val, Number and IP are heading in the csv file and the second line i.e., FirstVal, SecondVal etc are the values of those headers. I want to read only the values and

You can set i to a key word argument with a default of 1 then on each exception pass the current i when you restart your function so it picks up from there.

This is a simplified example of what I'm recommending following the same general method you are using in your question (but with fake data so I can run it without having your CSV file).

def my_function(i=1):
    try:
        if i == 4:  # to prevent forever recursion
            return
        else:
            print(i)  # keep track of loops
            i += 1
            x = int('te')   # causes an error
    except ValueError:
        my_function(i)   # send current i back through

my_function(i=0)

Continue Package Execution After Error in SSIS, The net result is that any error in this data flow task will still be shown as log the file-by-file results (success or failure, along with row count). Also, make sure to enter the exit line at the bottom of the batch file in case Windows cannot restart the computer because of the open MS-DOS window. Microsoft Windows 98 and Windows ME users can also run the following command to perform different forms of rebooting or shutting down.

thank you for your quick response .. i tried the solution provided by –Kevin Welch and –Selcuk it works fine for me thx here is the solution

def my_function():
try :
    with open('file.csv', 'r') as f:
        data = list(csv.reader(f, delimiter=','))

        i = 1
        while i <= 10:
            i += 1
            try :

                fname = data[i][0]
                lname = data[i][1]

                options = Options()
                driver = webdriver.Chrome(options=options)
                driver.get("https://www.test.net/")

                # Do staff

            except Exception as e:
            print(e)
            driver.quit()
            time.sleep(1)
            print('******RESTAR******')
            continue

my_function()

fputcsv - Manual, fputcsv — Format line as CSV and write to file pointer array and just include it as the first row of the data, but it is often useful to keep this data stored in different​  Press Windows key + R to open up a Run dialog box. Then, type “control” and press Enter to open up the classic Control Panel interface.; Once you’re inside the control panel window, use the search function in the top-right corner to search for “internet options“.

How to avoid ANSYS APDL from shutting automatically without any , How to avoid ANSYS APDL from shutting automatically without any error on line in your script right after /solu command and then see what happens. I am facing the same problem now, when trying to restart a coupled pore fluid *​CFOPEN,results,csv !create file to comma separated value or. Continue with LinkedIn. Here is a simple trick that I used to restart my python script after unhandled exception. Let’s say I have this simple script called test.py that I want to run forever. It will just wait 2 seconds and…

PHP Error Handling, An error message with filename, line number and a message describing the error is sent to the browser. The first example shows a simple script that opens a text file: However, simply stopping the script is not always the right way to go. The script found something that might be an error, but could also happen when  Option 2: Delete the entries after userinit.exe. Open the Registry Editor as described in Step 1 of the previous method.; From the left navigation pane, expand the following folders: HKEY_LOCAL_MACHINE, then SOFTWARE, then Microsoft, then Windows NT, followed by CurrentVersion and in the end, click on Winlogon.

Handling Errors the PowerShell Way, Summary: Trevor Sullivan talks about handling errors in Windows that errors will be written out to the host, but the script will continue to  1. You can open the file in a text reader and save it again with the UNIX line breaks. 2. You can use a utility like fromdos or dos2unix to convert the file. 3. You can use a vi command like this to replace the line breaks with the correct ones: :%s/^M/^M/g. Hint: The trick here is in how you enter the command.

Comments
  • Not really understanding what you mean, but if I had to guess it would be that you want to continue through the loop if an error is thrown, rather than restart the whole function. Why not just put your try/except inside of your while loop?
  • You should catch the exception inside the while loop and continue instead of calling the function again. You will end up with a stack overflow if you keep recursing endlessly like you are currently doing.
  • i'll try to implant this solution .. thank you for your contribution
  • Great, please click the checkmark next to the answer and vote if it answers your question. Comment here if you need more help with implementing it.