如何用Python的subprocess.Popen执行指定wget查询命令?
Hey there! Let's get that wget query running smoothly with subprocess.Popen. There are two primary approaches, each with its own pros—here's how to implement both:
Recommended: Shell=False (Safer, No Injection Risk)
This is the best practice because it avoids shell parsing, eliminating security risks if your command ever includes untrusted input. You'll split the command into a list of individual arguments:
import subprocess # Break the command into a list of components wget_command = [ "wget", "https://www.uniprot.org/uniprot/?query=CDK10+AND+organism:9606+AND+gene_exact:cdk10&columns=id&format=tab" ] # Execute the command, capturing stdout/stderr as text process = subprocess.Popen( wget_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # Retrieve output and wait for the process to finish stdout, stderr = process.communicate() # Check if the command succeeded if process.returncode == 0: print("Command ran successfully!") print("Output:\n", stdout) else: print("Oops, an error occurred:") print(stderr)
If you want wget to save results directly to a specific file (instead of printing to stdout), add the -O flag and your filename to the command list:
wget_command = [ "wget", "-O", "cdk10_results.txt", "https://www.uniprot.org/uniprot/?query=CDK10+AND+organism:9606+AND+gene_exact:cdk10&columns=id&format=tab" ]
Alternative: Shell=True (Simpler, But Less Secure)
If you're working with a trusted command and don't want to split arguments, you can pass the full command as a string with shell=True. Just be aware this is risky if your command includes user-provided input:
import subprocess # Full command as a single string wget_command = 'wget "https://www.uniprot.org/uniprot/?query=CDK10+AND+organism:9606+AND+gene_exact:cdk10&columns=id&format=tab"' process = subprocess.Popen( wget_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) stdout, stderr = process.communicate() if process.returncode == 0: print("Success!") else: print("Error message:", stderr)
Key Notes:
- Use
text=True(oruniversal_newlines=Truein older Python versions) to get output as strings instead of bytes. communicate()waits for the process to finish and captures all output—this is better than reading stdout/stderr directly to avoid deadlocks.
内容的提问来源于stack exchange,提问作者Tal

