You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的subprocess.Popen执行指定wget查询命令?

Using subprocess.Popen with Your wget Command

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:

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 (or universal_newlines=True in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:57:05