【问题标题】:Is there any modification to execute curl command in python 3.x?在 python 3.x 中执行 curl 命令是否有任何修改?
【发布时间】:2021-01-29 14:45:38
【问题描述】:

我在 python 2.x 版本中有一个用于以下 shell 命令的可运行代码:

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

python 2.x 的脚本如下:

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)

但是当在 Python 3.x 版本中执行相同的脚本时:

它给出的错误如下:

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

  • 请告诉我应该对代码进行哪些更改,以便在 Python 3.x 版本中执行。 python 3.x 版本需要哪些先决条件?

【问题讨论】:

  • 这能回答你的问题吗? Import error: No module name urllib2
  • 只要搜索 No module named 'urllib2' 就足够了
  • 我试过了,但在这种情况下,我已经在后端训练了 rasa-nlu 模型并尝试以 json 格式提取数据。我以这种方式更改了代码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)
  • 出现以下错误:Traceback (most recent call last): File "code.py", line 11, in &lt;module&gt; 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.

标签: python-3.x curl urllib urllib2 python-2.x


【解决方案1】:

我在不使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 2018-10-04
    • 2014-11-17
    • 1970-01-01
    • 2012-11-26
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多