티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to use Python to execute a cURL command?

파이썬을 사용하여 cURL 명령을 실행하는 방법은?

 문제 내용 

I want to execute a curl command in Python.

나는 파이썬에서 curl 명령을 실행하고 싶다.

 

Usually, I just need to enter the command in the terminal and press the return key. However, I don't know how it works in Python.

보통 나는 단말기에 명령어를 입력하고 리턴 키를 누르면 된다. 하지만 파이썬에서 어떻게 작동하는지는 모르겠어요.

 

The command shows below:

명령은 다음과 같습니다.

 

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

There is a request.json file to be sent to get a response.

응답을 받기 위해 보낼 request.json 파일이 있습니다.

 

I searched a lot and got confused. I tried to write a piece of code, although I could not fully understand it and it didn't work.

나는 검색을 많이 해서 헷갈렸어. 나는 코드를 하나 작성하려고 했지만, 완전히 이해할 수 없었고, 그것은 작동하지 않았다.

 

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()

The error message is Parse Error. How to get a response from the server correctly?

오류 메시지는 구문 분석 오류입니다. 서버에서 응답을 올바르게 받는 방법은 무엇입니까?

 

 

 

 높은 점수를 받은 Solution 

For the sake of simplicity, you should consider using the Requests library.

단순성을 위해 requests 라이브러리를 사용하는 것을 고려해야 합니다.

 

An example with JSON response content would be something like:

JSON 응답 콘텐츠의 예는 다음과 같습니다.

 

import requests
r = requests.get('https://github.com/timeline.json')
r.json()

If you look for further information, in the Quickstart section, they have lots of working examples.

자세한 내용을 보려면 빠른 시작 섹션에 많은 작업 예제가 있습니다.

 

For your specific curl translation:

특정 curl 변환의 경우:

 

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)

 

 

 가장 최근 달린 Solution 

I use os library.

나는 os 라이브러리를 사용한다.

 

import os

os.system("sh script.sh")

script.sh literally only contains the curl.

script.sh은 문자 그대로 컬만 포함한다.

 

 

 

출처 : https://stackoverflow.com/questions/25491090/how-to-use-python-to-execute-a-curl-command

반응형
댓글
공지사항
최근에 올라온 글