1

I'm trying to retrieve a python list that generates from an external python file(algorithm.py). In algorithm.py has a set of functions that used to generate a python list. There is no issue with algorithm.py file and it generates the python list as I expect. I followed the below steps to get the python list which generates in algorithm.py into views.py.

1.) Pass a variable(lec_name) from a function in views.py to algorithm.py and retrieve the output by using stdout as the below statement.

lec_name = request.POST['selected_name']
result = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE)

2.) And then when I print(result.stdout), I receive the output(the python list which I expect) as an array of byte as below.

b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]\r\n"

3.) Then I used print((result.stdout).strip()) to remove \r\n and It gives output as below.

b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]"

This gives the python list which I expect as an array of byte So what I need, retrieve the output(the python list which I expect) as a python list. How can I solve this? I tried lot of things, but none succeeded. I'm using Python 3.7.4, Django 3.0.1

Gabio
  • 9,126
  • 3
  • 12
  • 32
BK94
  • 59
  • 1
  • 11

1 Answers1

1

Try to use literal_eval, which Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression:

import ast
data  = b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]"

data_list = ast.literal_eval(data.decode())
print(type(data_list)) # output: <class 'list'>
print(data_list) # output: [['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]

Gabio
  • 9,126
  • 3
  • 12
  • 32