파이썬에서 curl 명령을 실행하고 싶습니다.
일반적으로 터미널에 명령을 입력하고 Enter 키를 누르면됩니다. 그러나 파이썬에서 어떻게 작동하는지 모르겠습니다.
명령은 다음과 같습니다.
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
응답을 얻기 위해 request.json 파일을 보내야합니다.
나는 많은 것을 찾고 혼란스러워했다. 완전히 이해할 수는 없지만 코드를 작성하려고했습니다. 작동하지 않았다.
import pycurl
import StringIO
response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '@request.json')
c.perform()
c.close()
print response.getvalue()
response.close()
오류 메시지는 ‘Parse Error’입니다. 누구나 문제를 해결하는 방법을 알려줄 수 있습니까? 또는 서버에서 올바르게 응답을 얻는 방법은 무엇입니까?
답변
간단하게하기 위해 요청 라이브러리 사용을 고려해야 합니다.
json 응답 내용의 예는 다음과 같습니다.
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
추가 정보를 찾으려면 빠른 시작 섹션에서 많은 작업 예제가 있습니다.
편집하다:
특정 컬 번역의 경우 :
import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)
답변
이 웹 사이트를 사용 하십시오 . curl 명령을 Python, Node.js, PHP, R 또는 Go로 변환합니다.
예:
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf
파이썬에서 이것이됩니다.
import requests
headers = {
'Content-type': 'application/json',
}
data = '{"text":"Hello, World!"}'
response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)
답변
import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json
아마도?
파일을 보내려고하는 경우
files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json
아아 감사합니다 @LukasGraf 지금은 원래 코드가 무엇을하는지 더 잘 이해합니다.
import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print
print req.json # maybe?
답변
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
파이썬 구현은
import requests
headers = {
'Content-Type': 'application/json',
}
params = (
('key', 'mykeyhere'),
)
data = open('request.json')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)
답변
내 대답은 WRT python 2.6.2입니다.
import commands
status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")
print output
필요한 매개 변수를 제공하지 않아서 죄송합니다.
답변
일부 배경 : 내용을 검색하기 위해 무언가를해야했기 때문에이 질문을 정확하게 찾아 갔지만 SSL 지원이 부적절한 이전 버전의 Python 만 사용할 수있었습니다. 구형 MacBook을 사용하고 있다면 내가 말하는 것을 알고 있습니다. 어쨌든 curl
셸에서 잘 실행되므로 (현대 SSL 지원이 연결되어 있다고 생각합니다) 때로는 requests
또는 을 사용하지 않고이 작업을 수행하려고합니다 urllib2
.
subprocess
모듈을 사용 curl
하여 검색된 컨텐츠 를 실행 하고 가져올 수 있습니다.
import subprocess
// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])
Python 3의 subprocess
모듈에는 .run()
여러 유용한 옵션이 포함되어 있습니다. 실제로 파이썬 3을 실행하는 사람에게 그 대답을 제공하도록 남겨 두겠습니다.
답변
이것은 아래 언급 된 의사 코드 접근 방식으로 달성 할 수 있습니다
가져 오기 os 가져 오기 요청 Data = os.execute (curl URL) R = Data.json ()