Home>

A program that measures the speed of the network and writes/adds to the CSV file
We have created it, but at the following two places,NameErrorxxx date_str is not defined (it is not defined) will occur.

Function to create/add CSV filedef get_Speed_File (speedData):At the inner
Should it be defined as a variable, and if so, how should it be defined?
Ordef get_Speed_File (speedData):Is the argument passed to wrong?
I don't know.

I would appreciate it if you could teach me.

writer.writerow ([date_str, time_str, mbps_down_result, mbps_up_result])
writer.writerow ({'Date': date_str,'Time': time_str,'Download': mbps_down_result,'UPload': mbps_up_result})
import csv
import os
import datetime
import speedtest
# Create/add CSV file to describe measurement result
def get_Speed_File (speedData):
    f_name ='SpeedTest.csv'
    If # SpeedTest.csv exists, add the result
    if (os.path.exists (f_name)):
        with open (f_name,'a', newline ='') as csv_file:
            writer = csv.writer (csv_file)
            writer.writerow ([date_str, time_str, mbps_down_result, mbps_up_result])
    else: else:
    If # SpeedTest.csv does not exist, create speedTest.csv and describe the measurement result.
    The #fields are "Measurement date (YYYY/MM/DD)", "Measurement execution time (HH: MM)", "Download speed", and "Upload speed".
        with open (f_name,'w', newline ='') as csv_file:
            filednames = ['Date','Time','Download','UPload']
            writer = csv.DictWriter (csv_file, fieldnames = filednames)
            writer.writeheader ()
            writer.writerow ({'Date': date_str,'Time': time_str,'Download': mbps_down_result,'UPload': mbps_up_result})
def get_speed_test ():
    servers = [28910, 20976]
    stest = speedtest.Speedtest ()
    stest.get_servers (servers)
    stest.get_best_server ()
    return stest

def command_line_runner ():
    # Set "Measurement date (YYYY/MM/DD)" and "Measurement execution time (HH: MM)"
    tmp_day = datetime.date.today ()
    tmp_time = datetime.datetime.today ()
    date_str = tmp_day.strftime ('% Y /% m /% d')
    time_str = tmp_time.strftime ('% H:% M')
    stest = get_speed_test ()
    down_result = stest.download ()
    up_result = stest.upload ()
    mbps_down_result = int (down_result/1024/1024)
    mbps_up_result = int (up_result/1024/1024)
    # "Measurement date (YYYY/MM/DD)" "Measurement execution time (HH: MM)" "Download speed" "Upload speed"
    # Store the measurement result in the result variable
    result = [date_str, time_str, mbps_down_result, mbps_up_result]
    # SpeedTest.csv Function call to create/add. Set the measurement result (result) in the argument
    get_Speed_File (result)
    print (result)
command_line_runner ()
  • Answer # 1

    Break down the list received by the get_Speed_File function under the name speedData into each variable.

    # Create/add CSV file to describe measurement result
    def get_Speed_File (speedData):
        f_name ='SpeedTest.csv'
        date_str, time_str, mbps_down_result, mbps_up_result = speedData #<===== Add this line
    (Omitted below)

    Would it be as follows if it is organized as a whole?
    -The write_data function converts the argument from a list to a dictionary. If you pass a dictionary to .writerow, you can automatically associate the key with the header and write it.
    -If mode ='a' is specified in open and the file does not exist, a new file is automatically created. This will reduce the number of lines.
    However, if you want to limit the writing of the header only when creating a new file, you need to check the existence of the existing file as shown below (is_new_file part).

    import csv
    import os
    import datetime
    import speedtest
    # Create/add CSV file to describe measurement result
    #Receives a dictionary with Date, Time, Download, Upload as arguments.
    def write_data (result):
        f_name ='SpeedTest.csv'
        A flag that indicates whether # SpeedTest.csv is a new file
        is_new_file = False if os.path.exists (f_name) else True
        Create # speedTest.csv and describe the measurement result
        # If the file does not exist, it will be newly created, and if the file exists, it will be added.
        with open (f_name,'a', newline ='') as csv_file:
            The #fields are "Measurement date (YYYY/MM/DD)", "Measurement execution time (HH: MM)", "Download speed", and "Upload speed".
            writer = csv.DictWriter (csv_file, fieldnames = result.keys ())
            Write header only if # SpeedTest.csv is a new file
            if is_new_file:
                writer.writeheader ()
            # Write the result to a file
            writer.writerow (result)
    def get_speed_test ():
        servers = [28910, 20976]
        stest = speedtest.Speedtest ()
        stest.get_servers (servers)
        stest.get_best_server ()
        return stest
    def command_line_runner ():
        # Set "Measurement date (YYYY/MM/DD)" and "Measurement execution time (HH: MM)"
        tmp_day = datetime.date.today ()
        #Measurement date (YYYY/MM/DD)
        date_str = tmp_day.strftime ('% Y /% m /% d')
        #Measurement time (HH: MM)
        time_str = tmp_day.strftime ('% H:% M')
        #Measure speed.
        stest = get_speed_test ()
        down_result = stest.download ()
        up_result = stest.upload ()
        # "Measurement date (YYYY/MM/DD)" "Measurement execution time (HH: MM)" "Download speed" "Upload speed"
        # Store the measurement result in the result variable
        result = {
            "Date": date_str,
            "Time": time_str,
            "Download": int (down_result/1024/1024),
            "Upload": int (up_result/1024/1024)
        }
        # Write the result
        write_data (result)
        print (result)
    command_line_runner ()