събота, 28 март 2020 г.

[SnakeData] {create_template( ), run_script( ), cd( )}

    The functions in the article title are with relatively short syntax and that's why I decided to write a single article for all three of them instead of having one small article per function. So, let's begin!
    create_template(temp_name, var_list) - this function generates a csv file that contains desired list of variables to be extracted from csv data files in folder "data". temp_name argument should be replaced by the template file name (e.g. "all.csv") when calling the function. var_list needs to be replaced by a list of strings containing the names of all variables we need (e.g. ["q1","q2","q4"]). Syntax below:


  1. def create_template(temp_name,var_list):
  2.     with open('templates/'+temp_name,'w') as tp:
  3.         temp_writer=csv.writer(tp,delimiter=",")
  4.         temp_writer.writerow(var_list)


I guess you noticed I didn't close the file after opening it - with open handles file opening and closure by itself and it is not needed to write tp.close() when we don't need the file anymore. The code looks like below when calling the function:

create_template("all.csv",["q1","q2","q4"])

    run_script(script_file) -  this function is quite simple and I have created it to allow execution of custom python scripts:

  1. def run_script(script_file):
  2.     exec(open("scripts/"+script_file).read())

The script_file argument should be replaced by existing file that contains valid Python code. This file should be located in folder "scripts" in order to work. And that's it, exec() is able to execute valid Python code written in any text format so it is not mandatory your script files to end with ".py".

    cd(folder) - this one was written to replicate the "cd" command from bash into SnakeData terminal: 

  1. def cd(folder):
  2.     if folder=='..':
  3.         os.chdir('..')
  4.     elif os.path.isdir(folder):
  5.         os.chdir(folder)
  6.     else:
  7.         print("Incorrect path")

If folder argument is equal to ".." then the SnakeData console returns one folder back. If folder has a value different than ".." the program checks whether this value is equal to the name of existing folder and if it is - working directory is changed to the respective folder. If none of conditions on rows 2 and 4 is sattisfied then the "Incorrect path" message is printed and execution stops.

Code processed by pastebin.


Няма коментари:

Публикуване на коментар