如何解决IronPython执行时出现的‘913不在要求范围内’错误?
Hey there, let's break down this issue and figure out how to fix it. First, let's recap what we know: your Python crawler works fine on its own, but when you call it from C# using IronPython, you hit the "913 is not in required range" error at the Execute(scope) step. Here's what's likely going on and how to resolve it:
Most Common Culprit: IronPython <-> CPython Version Mismatch
Looking at your C# code, you're adding both IronPython 2.7 and CPython 3.6 paths to the engine's search paths. That's a red flag because:
- IronPython is built to be compatible with Python 2.7, not Python 3.x. CPython 3.6 has syntax, library, and Unicode handling differences that IronPython doesn't support.
- Mixing these paths creates conflicts—IronPython might try to load Python 3.x libraries that use unsupported features, leading to unexpected errors like the 913 range issue.
Fix Step 1: Remove CPython 3.6 Paths
First, strip out all CPython 3.6 references from your search paths. Your C# code should only include IronPython's library path:
var engine = IronPython.Hosting.Python.CreateEngine(); var searchPaths = engine.GetSearchPaths(); searchPaths.Add(@"C:\Program Files\IronPython 2.7\Lib"); // Remove all CPython 3.6 paths here engine.SetSearchPaths(searchPaths);
Fix Step 2: Make Your Crawler Python 2.7 Compatible
Since IronPython runs Python 2.7, your crawling.py needs to avoid Python 3.x-specific features. Check for these common issues:
- Print statements: Replace
print("text")withprint "text"(no parentheses). - String encoding: Python 2 uses
strfor bytes andunicodefor text—ensure your crawler handles encoding correctly (e.g., useunicode()instead ofstr()for text, or decode bytes properly). - Dictionary methods: In Python 3,
dict.items()returns an iterator; in Python 2, it returns a list. If you're iterating over items, use.items()(IronPython 2.7 supports both, but avoid any Python 3-only iterator logic). - F-strings: Replace
f"Hello {url}"with"Hello {}".format(url).
Digging Into the "913 is not in required range" Error
The 913 error specifically relates to Unicode character range validation in IronPython. Unlike CPython, IronPython has stricter checks for valid Unicode code points. If your crawler returns content with rare or invalid Unicode characters (e.g., some emoji, legacy symbols), IronPython might reject them.
Fix for Unicode Issues
Add encoding handling in your Python script to sanitize the output before returning it to C#:
def setURL(url): # Your existing crawling logic here raw_data = your_crawling_function(url) # Sanitize Unicode characters to avoid range errors # Option 1: Remove invalid characters cleaned_data = ''.join(c for c in raw_data if ord(c) <= 0x10FFFF) # Option 2: Encode/decode to handle problematic characters cleaned_data = raw_data.encode('utf-8', errors='replace').decode('utf-8') return cleaned_data
If Python 2.7 Isn't an Option: Switch to Python.NET
If your crawler relies heavily on Python 3.x libraries or features that can't be ported to 2.7, ditch IronPython and use Python.NET (pythonnet) instead. It lets you call CPython 3.x directly from C# with full compatibility.
Example C# Code with Python.NET
First, install the Python.Runtime NuGet package. Then use this code:
using Python.Runtime; // Initialize CPython 3.6 Runtime.PythonDLL = @"C:\Users\AppData\Local\Programs\Python\Python36-32\python36.dll"; PythonEngine.PythonPath = @"C:\Users\AppData\Local\Programs\Python\Python36-32\Lib;C:\Users\AppData\Local\Programs\Python\Python36-32\Lib\site-packages"; PythonEngine.Initialize(); try { using (Py.GIL()) // Acquire the Global Interpreter Lock { string URL = URLTB.Text.Trim(); dynamic crawlingScript = Py.Import("crawling"); dynamic data = crawlingScript.setURL(URL); // Process your data here } } catch (Exception ex) { MessageBox.Show("Crawling error : " + ex.Message); } finally { PythonEngine.Shutdown(); }
Test with a Minimal Script
To isolate the issue, create a simplified crawling.py and test if your C# code works:
def setURL(url): return "Received URL: {}".format(url) # For IronPython 2.7 # Or for Python.NET (3.x): return f"Received URL: {url}"
If this works, gradually reintroduce your crawler's logic until you find the exact code that triggers the error.
内容的提问来源于stack exchange,提问作者SuYeon Choi

