如何在Python中执行curl命令?含指定curl命令实现需求
Let's walk through how to replicate this curl command in Python— I'll cover two common approaches, depending on whether you want to use a popular third-party library or stick to built-in tools.
Your original curl command:
curl -H 'Content-Type: application/x-ndjson' -XPOST '192.168.1.149:9200/shakespeare/doc/_bulk?pretty' --data-binary @file.json
Approach 1: Using the requests Library (Recommended)
This is the most straightforward and readable way, since requests abstracts away a lot of the low-level HTTP stuff. First, make sure you have it installed:
pip install requests
Then here's the equivalent Python code:
import requests # Define the target URL and headers url = 'http://192.168.1.149:9200/shakespeare/doc/_bulk?pretty' headers = {'Content-Type': 'application/x-ndjson'} # Read the file in binary mode (matches --data-binary) with open('file.json', 'rb') as f: data = f.read() # Send the POST request try: response = requests.post(url, headers=headers, data=data) # Print the pretty-printed response (since we added ?pretty to the URL) print(response.text) except requests.exceptions.RequestException as e: print(f"An error occurred: {e}")
Breakdown:
headersmaps directly to the-Hflag in curlrequests.post()handles the-XPOSTmethod- Reading the file with
rbmode ensures we send binary data, just like--data-binary - The
try/exceptblock catches common issues like network errors or invalid responses
Approach 2: Using Built-in urllib.request (No Extra Installs)
If you can't or don't want to install external libraries, Python's standard library has you covered with urllib:
import urllib.request url = 'http://192.168.1.149:9200/shakespeare/doc/_bulk?pretty' headers = {'Content-Type': 'application/x-ndjson'} # Read the file binary data with open('file.json', 'rb') as f: data = f.read() # Create the request object req = urllib.request.Request(url, data=data, headers=headers, method='POST') try: with urllib.request.urlopen(req) as response: # Read and decode the response print(response.read().decode('utf-8')) except urllib.error.URLError as e: print(f"An error occurred: {e}")
Breakdown:
- We create a
Requestobject that specifies the URL, data, headers, and method (POST) urlopen()sends the request, and we read/decode the response to get the human-readable output- This does the exact same thing as the curl command, just using Python's built-in tools
Either of these should work perfectly for your use case. The requests approach is generally preferred for its simplicity and cleaner syntax, but the urllib method is great for environments where you can't install additional packages.
内容的提问来源于stack exchange,提问作者Prophet

