Source code string cannot contain null bytes ошибка

I’m using Max OS X 10.10.3, and I finally got the graphics.py to show in Python 3, before it was saying no module existed.

However, now when I try import graphics, or from graphics import *, I get the message:

"source code string cannot contain null bytes"

Does any Mac user (using Python 3) perhaps know what is wrong? Has anyone used the Zelle book and his graphics.py module? Thanks.

WhiZTiM's user avatar

WhiZTiM

21.1k4 gold badges42 silver badges68 bronze badges

asked Jul 5, 2015 at 18:46

Peter G. Williams's user avatar

5

For posterity: I had the same problem and fixed it using,

sed -i 's/x0//g' FILENAME

The file seemed to be messed up in numerous ways (wrong endings, etc); no idea how…

See https://stackoverflow.com/a/2399817/230468

Community's user avatar

answered Aug 22, 2016 at 19:39

DilithiumMatrix's user avatar

DilithiumMatrixDilithiumMatrix

17.5k22 gold badges76 silver badges118 bronze badges

1

I am using Visual Studio Code, the encoding was set to UTF-16 LE.
You can check the encoding on the right bottom side of VSCode. Just click on the encoding and select «save with encoding» and select UTF-8. It worked perfectly.

answered Jun 13, 2019 at 4:42

Paco Meraz's user avatar

1

I got this message when I wanted to use eval for my input for my function that sometimes it takes string or int/float but when it takes numpy numbers, it throws this exception, eval(number).

My solution was eval(str(number)).

answered Aug 5, 2019 at 6:09

Habib Karbasian's user avatar

I just encountered this problem, which is usually caused by the encoding format. You can use Notepad++ to change the encoding format of python files to UTF-8.

answered Nov 28, 2018 at 3:20

Chaplin Hwang's user avatar

This kind of error is not from your project source code. This kind of error emerges from your python interpreter. So the best solution is to set your python interpreter in your project env directory. or set the interpreters virtual env properly using your IDE’s interpreter configuration.

answered Apr 23, 2016 at 9:15

Open your file with an editor that can show you all invisible character.
You will see where is the invalid char, just delete and re-type it.

If you are on mac you can do it with Coda > Open your file > Show invisible characters.

answered Apr 16, 2019 at 9:20

Fabio Caccamo's user avatar

1

  • Go to python folder python36/Lib/site-packages/scipy/
  • Open __init__.py

Change:

from scipy._lib._testutils import PytestTester

to:

from scipy._lib.test__testutils import PytestTester

It worked on my windows 7

Jay Dorsey's user avatar

Jay Dorsey

3,5232 gold badges18 silver badges24 bronze badges

answered Jul 26, 2019 at 16:30

Atharva Panage's user avatar

1

I created a file using windows terminal echo «hello» > hello.py and got this issue. I resolved by creating a new file from notepad

answered May 30, 2021 at 6:42

Janarthanan Ramu's user avatar

My problem was the python interpreter, try changing it to the right python directory path

answered Nov 18, 2021 at 14:55

Harel Malichi's user avatar

1

Do you experience getting the error message “source code string cannot contain null bytes“, whenever you attempt to import graphics, or from graphics import *? .This warning message is shown if the contents of the file include a byte that has a value that is a null value.

What is ValueErrror?

ValueError is the error in python that mostly occurs when you are passing the argument to the built-in functions of the right type. But the value of that argument is invalid. For example, suppose the function accepts an argument of integer type. And you are passing the value by converting the string to an integer. In this case, you will get the ValueErrror.

Solution for the source code string cannot contain null bytes

If you have been experiencing “source code string cannot contain null bytes” problem, then the following possible options may help you fix it:

Solution 1: Remove the null character

Remove the null character at the end of line 41 in the cTurtle.py because, for some unknown reason, line 41 of the cTurtle.py file includes a null character:

$ od -t a cTurtle.py.orig | grep -i nul

0003360 - - - - sp c T u r t l e . p y nul

After the removal of the null character, the module’s operations should go back to their normal state.

Solution 2: Use the sed command

If you want to remove the null characters that are in a file, you may do it quickly and simply by using the sed command that is indicated in the following example:

sed -i 's/x0//g' FILENAME

This method modifies the file in situ, which is critical if the file is still being used. Passing the parameter -i’ext’ generates a backup of the original file with the ‘ext’ suffix appended to it.

Solution 3: Use pipeline

In the event that the output of sed indicates that nothing was replaced, then you may make use of the following pipeable one-liner using Phyton:

python -c 'import sys; sys.stdout.write(sys.stdin.read().replace("", ""))'

You may also discover that some instructions do, in fact, leave the null bytes in place, despite the fact that they are no longer visible, at least not in a terminal running OS X. Hexdump is a useful tool for debugging situations like these.

Conclusion

ValueError is a python exception error that you will get when you are passing the argument to the function of an invalid type. The Valueerror: source code string cannot contain null bytes also comes due to this case. The above method will solve your problems regarding this error.

Traceback (most recent call last):
File «C:UsersINTELAppDataLocalProgramsPythonPython39Scriptspip-script.py», line 33, in
sys.exit(load_entry_point(‘pip==21.1.1’, ‘console_scripts’, ‘pip’)())
File «C:UsersINTELAppDataLocalProgramsPythonPython39Scriptspip-script.py», line 25, in importlib_load_entry_point
return next(matches).load()
File «c:usersintelappdatalocalprogramspythonpython39libimportlibmetadata.py», line 77, in load
module = import_module(match.group(‘module’))
File «c:usersintelappdatalocalprogramspythonpython39libimportlib_init_.py», line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File «», line 1030, in _gcd_import
File «», line 1007, in _find_and_load
File «», line 986, in _find_and_load_unlocked
File «», line 680, in _load_unlocked
File «», line 855, in exec_module
File «», line 228, in _call_with_frames_removed
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_internalclimain.py», line 9, in
from pip._internal.cli.autocompletion import autocomplete
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_internalcliautocompletion.py», line 10, in
from pip._internal.cli.main_parser import create_main_parser
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_internalclimain_parser.py», line 8, in
from pip._internal.cli import cmdoptions
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_internalclicmdoptions.py», line 23, in
from pip._internal.cli.parser import ConfigOptionParser
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_internalcliparser.py», line 12, in
from pip._internal.configuration import Configuration, ConfigurationError
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_internalconfiguration.py», line 27, in
from pip._internal.utils.misc import ensure_dir, enum
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_internalutilsmisc.py», line 38, in
from pip.vendor.tenacity import retry, stop_after_delay, wait_fixed
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_vendortenacity_init
.py», line 523, in
from pip.vendor.tenacity.tornadoweb import TornadoRetrying
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagespip_vendortenacitytornadoweb.py», line 23, in
from tornado import gen
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagestornadogen.py», line 81, in
from tornado.concurrent import (
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagestornadoconcurrent.py», line 34, in
from tornado.log import app_log
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagestornadolog.py», line 38, in
import colorama # type: ignore
File «c:usersintelappdatalocalprogramspythonpython39libsite-packagescolorama_init
.py», line 2, in
from .initialise import init,deinit,reinit,colorama_text
ValueError: source code string cannot contain null bytes

Since I am a Noob,I can’t understand the error here,can someone please explain what is wrong and how I can solve that

Many people ask questions like this, BUT many of them are using not standart library, so their error can be explained (for me). I used standart Tkinter library but i get this error too.

  File "C:/Users/Panda/Desktop/Пайтон/enter_symbol.py", line 5, in <module>
    exec(f'tk.bind({chr(num)},lambda event:print("You entered:",{chr(num)}))')
ValueError: source code string cannot contain null bytes

My code:

from tkinter import Tk
tk=Tk()
tk.geometry('0x0+0+0')
for num in range(1000):
    exec(f"""
try:tk.bind({chr(num)},lambda event:print("You entered:",{chr(num)}))
except:None""")

What should I do to not get this error?

Вопрос:

Я использую Max OS X 10.10.3, и я наконец получил graphics.py для показа в Python 3, прежде чем он сказал, что модуль не существует.

Однако теперь, когда я пытаюсь выполнить import graphics или from graphics import *, я получаю сообщение:

"source code string cannot contain null bytes"

Может ли любой пользователь Mac (используя Python 3) знать, что не так? Кто-нибудь использовал книгу Zelle и его модуль graphics.py? Спасибо.

Ответ №1

Для потомков: у меня была та же проблема и исправлено это с помощью

sed -i 's/x0//g' FILENAME

Файл, казалось, был испорчен множеством способов (неправильные окончания и т.д.); не знаю, как…

См. qaru.site/questions/89525/…

Ответ №2

Я только что столкнулся с этой проблемой, которая обычно вызывается форматом кодировки. Вы можете использовать Notepad++, чтобы изменить формат кодирования файлов Python на UTF-8.

Ответ №3

Откройте свой файл с помощью редактора, который может показать вам всех невидимых символов. Вы увидите, где находится недопустимый символ, просто удалите и введите его заново.

Если вы работаете на Mac, вы можете сделать это с помощью Coda> Открыть файл> Показать невидимые символы.

Ответ №4

Я использую код Visual Studio, кодировка была установлена в UTF-16 LE. Вы можете проверить кодировку в правой нижней части VSCode. Просто нажмите на кодировку и выберите “сохранить с кодировкой” и выберите UTF-8. Это сработало отлично.

Ответ №5

  • Перейти в папку python python36/Lib/site-packages/scipy/
  • Открыть __init__.py

Изменение:

from scipy._lib._testutils import PytestTester

в:

from scipy._lib.test__testutils import PytestTester

Он работал на моих окнах 7

Ответ №6

Я получил это сообщение, когда хотел использовать eval для ввода своей функции: иногда он принимает строку или int/float, но когда он принимает числа numpy, он выдает это исключение, eval(number).

Мое решение было eval(str(number)).

Ответ №7

Эта ошибка возникает не из исходного кода проекта. Такая ошибка возникает из вашего интерпретатора python. Поэтому лучшим решением является установка вашего интерпретатора python в каталог env. или правильно настроить интерпретаторы виртуального env, используя конфигурацию интерпретатора IDE.

Ответ №8

У меня такая же ошибка, и решение состоит в том, чтобы удалить библиотеку, и если вы не можете просто удалить ее и переустановить библиотеку. должен работать, он работает для меня…

Django Forum

Loading

Answer by Zavier Goodman

I am using google colab and I got the message: source code string cannot contain null bytes. Do you have any Idea how can I fix it?

– Sara

Apr 14 ’20 at 16:18

,

But how did you create this file? That should answer how you ended up with null bytes in the first place.

– user707650

Jul 5 ’15 at 22:27

,Connect and share knowledge within a single location that is structured and easy to search.,

Evert, I didn’t create the graphics.py module, it’s designed for beginners wanting an introduction to GUI in Python: mcsp.wartburg.edu/zelle/python

– Peter G. Williams

Jul 6 ’15 at 2:06

For posterity: I had the same problem and fixed it using,

sed -i 's/x0//g' FILENAME

Answer by Madilynn Phillips

Have you got a file called requests.py or a folder called requests?,im getting syntax error saying
source code cannot contain null bytes,

Pull requests
,File «C:UserstaimoorAppDataLocalProgramsPythonPython37libsite-packagesPIL_init_.py», line 17, in
from . import _version
ValueError: source code string cannot contain null bytes

Traceback (most recent call last):
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35librunpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35librunpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:UsersoverlapjhoAppDataLocalProgramsPythonPython35Scriptsjupyter-notebook.EXE__main__.py", line 5, in <module>
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35libsite-packagesnotebooknotebookapp.py", line 78, in <module>
    from .services.contents.manager import ContentsManager
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35libsite-packagesnotebookservicescontentsmanager.py", line 17, in <module>
    from nbformat import sign, validate as validate_nb, ValidationError
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35libsite-packagesnbformat__init__.py", line 33, in <module>
    from .validator import validate, ValidationError
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35libsite-packagesnbformatvalidator.py", line 12, in <module>
    from jsonschema import ValidationError
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35libsite-packagesjsonschema__init__.py", line 18, in <module>
    from jsonschema.validators import (
  File "c:usersoverlapjhoappdatalocalprogramspythonpython35libsite-packagesjsonschemavalidators.py", line 8, in <module>
    import requests
ValueError: source code string cannot contain null bytes

Answer by Davis Kline

I’m using Max OS X 10.10.3, and I finally got the graphics.py to show in Python 3, before it was saying no module existed.,To find the implementation of any python operator, first find out what bytecode Python generates for it, using the dis.dis function:,Another possibility is to write a simple Python script that reads the file and removes the null bytes use the string replace method:,The in operator becomes a COMPARE_OP byte code. Now you can trace how this opcode is being handled in the Python evaluation loop in Python/ceval.c:

However, now when I try import graphics, or from graphics import *, I get the message:

"source code string cannot contain null bytes"

Answer by Brynlee Bryant

The error message is ValueError: source code string cannot contain null bytes. Other newly installed libraries like pandas profiling are fine.,For installation I used pip install plotly_express.,Hi, plotly express is now (plotly >= 4.0) part of the potly module, plotly_express is a legacy module. You can import is as,I am trying to import plotly express unsuccessfully for several days. I already reinstalled but the problem continues. I’m with Python 3.7.3 installed by Anaconda and using Jupyter Notebook on Windows 10.

Log:

import plotly_express as px

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-eb81fef41697> in <module>
----> 1 import plotly_express as pxx

~AppDataLocalContinuumanaconda3libsite-packagesplotly_express__init__.py in <module>
      5 __version__ = "0.4.1"  # sync with setup.py!
      6 
----> 7 from plotly.express import *

~AppDataLocalContinuumanaconda3libsite-packagesplotly__init__.py in <module>
     28 from __future__ import absolute_import
     29 
---> 30 from plotly import (
     31     graph_objs,
     32     tools,

~AppDataLocalContinuumanaconda3libsite-packagesplotlyio__init__.py in <module>
----> 1 from ._orca import to_image, write_image
      2 from . import orca
      3 
      4 from ._json import to_json, from_json, read_json, write_json
      5 

~AppDataLocalContinuumanaconda3libsite-packagesplotlyio_orca.py in <module>
     12 from contextlib import contextmanager
     13 
---> 14 import retrying
     15 from six import string_types
     16 

ValueError: source code string cannot contain null bytes

Installation log:

PS C:Usersm2102884720Documents> pip install plotly_express
Collecting plotly_express
  Using cached https://files.pythonhosted.org/packages/d4/d6/8a2906f51e073a4be80cab35cfa10e7a34853e60f3ed5304ac470852a08d/p
lotly_express-0.4.1-py2.py3-none-any.whl
Requirement already satisfied: patsy>=0.5 in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packages (from
 plotly_express) (0.5.1)
Requirement already satisfied: statsmodels>=0.9.0 in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packag
es (from plotly_express) (0.10.0)
Requirement already satisfied: numpy>=1.11 in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packages (fro
m plotly_express) (1.16.4)
Requirement already satisfied: pandas>=0.20.0 in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packages (
from plotly_express) (0.24.2)
Collecting plotly>=4.1.0 (from plotly_express)
  Downloading https://files.pythonhosted.org/packages/f7/05/3c32c6bc85acbd30a18fbc3ba732fed5e48e5f8fd60d2a148877970f4a61/pl
otly-4.2.1-py2.py3-none-any.whl (7.2MB)
     |████████████████████████████████| 7.2MB 2.2MB/s
Requirement already satisfied: scipy>=0.18 in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packages (fro
m plotly_express) (1.2.1)
Requirement already satisfied: six in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packages (from patsy>
=0.5->plotly_express) (1.12.0)
Requirement already satisfied: python-dateutil>=2.5.0 in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-pa
ckages (from pandas>=0.20.0->plotly_express) (2.8.0)
Requirement already satisfied: pytz>=2011k in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packages (fro
m pandas>=0.20.0->plotly_express) (2019.1)
Requirement already satisfied: retrying>=1.3.3 in c:usersm2102884720appdatalocalcontinuumanaconda3libsite-packages
(from plotly>=4.1.0->plotly_express) (1.3.3)
Installing collected packages: plotly, plotly-express
Successfully installed plotly-4.2.1 plotly-express-0.4.1

Answer by Aryan Butler

(You can also just construct your particle effect via code–but that’s a much longer, more tedious, and less intuitive way of doing things.),Of course, this is all to be done only if Mac doesn’t let you just run the program directly from the file-manager, perhaps by double-clicking it, or by right-clicking it and selecting “run”.),Ah. You seem to be attempting to load an image as a particle effect. What “loadConfig” expects is instead a particle-definition file, such as saved from the Particle Panel sample-application.,I don’t use Mac, I’m afraid, so I don’t know where Panda gets installed on that platform. :/

Hi quick question, why does this error keep popping up when I try to do particle effects?

Known pipe types:
  CocoaGraphicsPipe
(all display modules loaded.)
2019-12-07 22:29:13.001 Python[9097:229512] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to (null)
:ParticleEffect(warning): loadConfig: failed to load particle file: '/Users/38167/PycharmProjects/viren/venv/wood.jpg'
Traceback (most recent call last):
  File "/Users/38167/PycharmProjects/viren/scene.py", line 155, in <module>
    app = MyApp()
  File "/Users/38167/PycharmProjects/viren/scene.py", line 18, in __init__
    p.loadConfig("/Users/38167/PycharmProjects/viren/venv/wood.jpg")
  File "/Users/38167/PycharmProjects/viren/venv/lib/python3.7/site-packages/direct/particles/ParticleEffect.py", line 206, in loadConfig
    exec(data)
ValueError: source code string cannot contain null bytes

here is a snippet of my code, I might be doing something wrong

from direct.particles.ParticleEffect import ParticleEffect

class MyApp(ShowBase):

    def __init__(self):
        ShowBase.__init__(self)
        base.enableParticles()
        p = ParticleEffect()
        p.loadConfig("/Users/38167/PycharmProjects/viren/venv/wood.jpg")
        p.start(parent=self.render, renderParent=self.render)

После восстановления (R.saver), папок проекта. Все как то и правильно и на месте. Но, не работает. Мистика. Может кто сталкивался?
Система и диск C — все новое. Есть два диска (не затронутых) «C + 2», один был полностью удален. Проекты на (не затронутых) дисках как работали так и работают. А, вот папки восстановленные с уничтоженного (коника выкидывают).В проекте только __init__.py = 0kb

python manage.py makemigrations
Traceback (most recent call last):
File «E:prazdnikmanage.py», line 11, in
execute_from_command_line(sys.argv)
File «C:UserspicasAppDataLocalProgramsPythonPython39libs ite-packagesdjangocoremanagement__init__.py», line 401, in execute_from_command_line
utility.execute()
File «C:UserspicasAppDataLocalProgramsPythonPython39libs ite-packagesdjangocoremanagement__init__.py», line 377, in execute
django.setup()
File «C:UserspicasAppDataLocalProgramsPythonPython39libs ite-packagesdjango__init__.py», line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File «C:UserspicasAppDataLocalProgramsPythonPython39libs ite-packagesdjangoappsregistry.py», line 122, in populate
app_config.ready()
File «C:UserspicasAppDataLocalProgramsPythonPython39libs ite-packagesdjangocontribadminapps.py», line 24, in ready
self.module.autodiscover()
File «C:UserspicasAppDataLocalProgramsPythonPython39libs ite-packagesdjangocontribadmin__init__.py», line 24, in autodiscover
autodiscover_modules(‘admin’, register_to=site)
File «C:UserspicasAppDataLocalProgramsPythonPython39libs ite-packagesdjangoutilsmodule_loading.py», line 47, in autodiscover_modules
import_module(‘%s.%s’ % (app_config.name, module_to_search))
File «C:UserspicasAppDataLocalProgramsPythonPython39libi mportlib__init__.py», line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File «», line 1030, in _gcd_import
File «», line 1007, in _find_and_load
File «», line 986, in _find_and_load_unlocked
File «», line 680, in _load_unlocked
File «», line 786, in exec_module
File «», line 923, in get_code
File «», line 853, in source_to_code
File «», line 228, in _call_with_frames_removed
ValueError: source code string cannot contain null bytes

Понравилась статья? Поделить с друзьями:
  • Source 11 brakes ошибка на камазе
  • Soundwire ошибка unable to connect soundwire server
  • Sound ошибка в стиральной машине
  • Sound forge ошибка при открытии кодека
  • Sotla ошибка авторизации 122 что делать