You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Python3.5中使用wp-cli遇subprocess.run语法错误,求正确写法

Fixing Syntax Errors with subprocess.run() for WP-CLI in Python 3.5

Hey there! Let's sort out that syntax error you're facing when trying to run WP-CLI commands via subprocess.run() in Python 3.5 and PyScripter. Most issues boil down to how you structure command arguments and use Python 3.5-specific subprocess parameters. Let's break this down step by step.

Common Pitfalls & Fixes

First, let's cover the mistakes that usually trigger syntax or runtime errors:

  • Forgetting to import the subprocess module entirely
  • Using text=True (a Python 3.7+ parameter) instead of universal_newlines=True (the Python 3.5 equivalent for string output)
  • Passing the entire WP-CLI command as a single string without setting shell=True (or vice versa)
  • Not specifying the correct working directory (cwd) where your WordPress installation lives

Correct Code Examples

This is the safer approach (avoids shell injection risks) and works reliably in Python 3.5. Split your WP-CLI command into a list of individual arguments:

import subprocess

# Split your WP-CLI command into a list of arguments
wp_cmd = ['wp', 'post', 'list', '--format=json', '--posts_per_page=5']

try:
    # Execute the command
    result = subprocess.run(
        wp_cmd,
        cwd='/path/to/your/wordpress/folder',  # Replace with your WP root directory
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,  # Returns output as string (Python 3.5 uses this instead of text=True)
        check=True  # Raises error if WP-CLI command fails (e.g., invalid args)
    )
    
    # Print successful output
    print("WP-CLI Results:\n", result.stdout)
except subprocess.CalledProcessError as e:
    # Handle WP-CLI command failures
    print("WP-CLI Command Failed:\n", e.stderr)
except FileNotFoundError:
    # WP-CLI isn't installed or not in system PATH
    print("Error: WP-CLI could not be found. Check if it's installed and in your PATH.")
except Exception as e:
    # Catch-all for other unexpected issues
    print("Unexpected Error:", str(e))

If you need to pass the command as a single string (e.g., complex commands with pipes), you can use shell=True—but be cautious if your command includes user input (risk of shell injection):

import subprocess

wp_cmd_str = 'wp post list --format=json --posts_per_page=5'

try:
    result = subprocess.run(
        wp_cmd_str,
        cwd='/path/to/your/wordpress/folder',
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        check=True
    )
    print("WP-CLI Results:\n", result.stdout)
except subprocess.CalledProcessError as e:
    print("Command Failed:\n", e.stderr)
except Exception as e:
    print("Error:", str(e))

Additional Tips

  • WP-CLI Path: If WP-CLI isn't in your system PATH, replace 'wp' with the full absolute path to the WP-CLI executable (e.g., '/usr/local/bin/wp' on Linux, 'C:\\wp-cli\\wp.exe' on Windows).
  • Test in Terminal First: Make sure your WP-CLI command runs correctly in your system terminal before adding it to Python code—this rules out WP-CLI configuration issues.
  • PyScripter Environment: Ensure PyScripter is using the correct Python 3.5 environment, and that the environment has access to WP-CLI (check PATH variables in PyScripter's settings).

内容的提问来源于stack exchange,提问作者Enrico Sartori

火山引擎 最新活动