-2

I have a runnable code in python 2.x version for following shell command :

curl -XPOST localhost:5055/parse -d '{"q":"tell me about more info on covid", "projects": "ChatBot"}'

script for python 2.x is as below :

import shutil
import sys
import urllib2
import subprocess
import json
import subprocess, sys
import os, time
import string
import os.path
import os, glob
from datetime import datetime

inputArg="tell me about more info on covid"
data = '{"q":"' + inputArg + '", "projects":"ChatBot"}'
url = 'http://localhost:5055/parse'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)

But when same script is executed in Python 3.x version:

it gives error as follows :

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import urllib2
ModuleNotFoundError : No module named 'urllib2'

  • Please let me know what changes shall be done in code so that it will execute in Python 3.x version. What are the pre-requisites needed in python 3.x version ?
user34
  • 103
  • 1
  • 1
  • 7
  • 1
    Does this answer your question? [Import error: No module name urllib2](https://stackoverflow.com/questions/2792650/import-error-no-module-name-urllib2) – Adam.Er8 Oct 15 '20 at 06:39
  • Just searching ```No module named 'urllib2'``` would've been enough – Abhinav Mathur Oct 15 '20 at 06:42
  • I have tried, but in this case I have trained rasa-nlu model in backend and trying to extract data in json format. I had changed code this way `import urllib.request inputArg="tell me about more info on covid" data = '{"q":"' + inputArg + '", "projects":"ChatBot"}' url = "http://localhost:5055/parse" request = urllib.request.Request(url) response = urllib.request.urlopen(request) data_content = response.read() print(data_content) ` – user34 Oct 15 '20 at 06:52
  • got following error: `Traceback (most recent call last): File "code.py", line 11, in response = urllib.request.urlopen(request) File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.6/urllib/request.py", line 524, in open req = meth(req) File "/usr/lib/python3.6/urllib/request.py", line 1255, in do_request_ raise TypeError(msg) TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.` – user34 Oct 15 '20 at 06:53

1 Answers1

0

I found the solution to this issue without using urllib.request:

$ cat test6.py
import requests
import json
inputArg="tell me about more info on covid"
data = {"q":inputArg , "projects":"ChatBot"}
params = json.dumps(data)
url = 'http://localhost:5055/parse'
r = requests.post(url, data=params)
print(r.text)
print(r.status_code, r.reason)
user34
  • 103
  • 1
  • 1
  • 7