Fayçal Borsali
Fayçal Borsali

Reputation: 424

Python notebook use return value from running a script

I am using a notebook (in Google Colab) in python 3 and really need to execute some python2 code with some data that is generated in my notebook !

So what I did was

  1. Generate the data in my cells AND save it to a file (data.txt)
  2. Write a python 2 script (myScript.py) with a main() function that parses the file from sys.argv[1] into data and than calls my python2 functions and do all the stuff then it ends with return results (which is a dictionary)
  3. In my notebook I run
!python2 myScript.py ./data.txt

(They are of course all in the same directory)

The command runs with no errors but no output ! How do I catch the results that are returned in a variable that I could use later ?


Not important but could be helpful :

Is there a better way to actually achieve what I am willing to achieve ?

Upvotes: 0

Views: 1053

Answers (1)

Fayçal Borsali
Fayçal Borsali

Reputation: 424

Thanks to @Manuel's comment on the question, I figured out this solution and it worked :

  1. In myScript.py, I changed return results by sys.stdout.write(json.dumps(results))
  2. In my notebook, I changed the cell that executes the script to this:
results = !python2 test_langdetect.py ./tmp_comments.txt
myVar = json.loads(results[0])

Of course you need to import json

Upvotes: 1

Related Questions