Skip to content

Prevent encoding error in IPython extension in Windows#342

Merged
Erotemic merged 1 commit into
pyutils:mainfrom
vnmabus:patch-1
May 22, 2025
Merged

Prevent encoding error in IPython extension in Windows#342
Erotemic merged 1 commit into
pyutils:mainfrom
vnmabus:patch-1

Conversation

@vnmabus
Copy link
Copy Markdown
Contributor

@vnmabus vnmabus commented May 18, 2025

When using the %lprun magic in Windows, and trying to store the profile results in a file, the following exception was raised if the functions profiled contain non-ASCII characters:

UnicodeEncodeError                        Traceback (most recent call last)
Cell In[5], line 1

File ...\.conda\Lib\site-packages\IPython\core\interactiveshell.py:2482, in InteractiveShell.run_line_magic(self, magic_name, line, _stack_depth)
   2480     kwargs['local_ns'] = self.get_local_scope(stack_depth)
   2481 with self.builtin_trap:
-> 2482     result = fn(*args, **kwargs)
   2484 # The code below prevents the output from being displayed
   2485 # when using magics with decorator @output_can_be_silenced
   2486 # when the last Python token in the expression is a ';'.
   2487 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):

File ...\.conda\Lib\site-packages\line_profiler\ipython_extension.py:161, in LineProfilerMagics.lprun(self, parameter_s)
    159 if text_file:
    160     pfile = open(text_file, "w")
--> 161     pfile.write(output)
    162     pfile.close()
    163     print(f"\n*** Profile printout saved to text file {text_file!r}. {message}")

File ...\.conda\Lib\encodings\cp1252.py:19, in IncrementalEncoder.encode(self, input, final)
     18 def encode(self, input, final=False):
---> 19     return codecs.charmap_encode(input,self.errors,encoding_table)[0]

UnicodeEncodeError: 'charmap' codec can't encode character '\u0394' in position 36719: character maps to <undefined>

This is because the default encoding in Windows does not support non-ASCII characters. Thus, the solution (as in #312) is to specify the UTF-8 encoding in the open call.

When using the `%lprun` magic in Windows, and trying to store the profile results in a file, the following exception was raised if the functions profiled contain non-ASCII characters:

```python
UnicodeEncodeError                        Traceback (most recent call last)
Cell In[5], line 1

File ...\.conda\Lib\site-packages\IPython\core\interactiveshell.py:2482, in InteractiveShell.run_line_magic(self, magic_name, line, _stack_depth)
   2480     kwargs['local_ns'] = self.get_local_scope(stack_depth)
   2481 with self.builtin_trap:
-> 2482     result = fn(*args, **kwargs)
   2484 # The code below prevents the output from being displayed
   2485 # when using magics with decorator @output_can_be_silenced
   2486 # when the last Python token in the expression is a ';'.
   2487 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):

File ...\.conda\Lib\site-packages\line_profiler\ipython_extension.py:161, in LineProfilerMagics.lprun(self, parameter_s)
    159 if text_file:
    160     pfile = open(text_file, "w")
--> 161     pfile.write(output)
    162     pfile.close()
    163     print(f"\n*** Profile printout saved to text file {text_file!r}. {message}")

File ...\.conda\Lib\encodings\cp1252.py:19, in IncrementalEncoder.encode(self, input, final)
     18 def encode(self, input, final=False):
---> 19     return codecs.charmap_encode(input,self.errors,encoding_table)[0]

UnicodeEncodeError: 'charmap' codec can't encode character '\u0394' in position 36719: character maps to <undefined>
```

This is because the default encoding in Windows does not support non-ASCII characters. Thus, the solution (as in pyutils#312) is to specify the UTF-8 encoding in the `open` call.
@codecov
Copy link
Copy Markdown

codecov Bot commented May 18, 2025

Codecov Report

Attention: Patch coverage is 0% with 1 line in your changes missing coverage. Please review.

Project coverage is 64.84%. Comparing base (96047f4) to head (b851fb6).
Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
line_profiler/ipython_extension.py 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main     #342   +/-   ##
=======================================
  Coverage   64.84%   64.84%           
=======================================
  Files          13       13           
  Lines        1041     1041           
  Branches      228      228           
=======================================
  Hits          675      675           
  Misses        306      306           
  Partials       60       60           
Files with missing lines Coverage Δ
line_profiler/ipython_extension.py 0.00% <0.00%> (ø)

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update ed3c320...b851fb6. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Erotemic
Copy link
Copy Markdown
Member

LGTM. Thanks for the patch!

@Erotemic Erotemic merged commit 662f11e into pyutils:main May 22, 2025
35 of 36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants