Qwertford Qwertford - 2 months ago 15
Python Question

Can't import subprocess module into python3

Im trying to import subprocess. However Im unable to even import subprocess.

Currently, my file (throwaway.py) consists of only one line:

import subprocess


but it returns the error:

Traceback (most recent call last):
File "throwaway.py", line 1, in <module>
import subprocess
ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 12, in <module>
import subprocess, tempfile, os.path, re, pwd, grp, os, time
ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n'

Original exception was:
Traceback (most recent call last):
File "throwaway.py", line 1, in <module>
import subprocess
ImportError: bad magic number in 'subprocess': b'\x03\xf3\r\n'


What are magic number errors? I read that they occur when you accidentally give a file the .pyc extention rather than .py?

Answer

In this case the error occurs because for some reason your code is importing Python 2.7 subprocess.pyc into Python 3. Python 2.7 .pycs start with b'\x03\xf3\r\n'. Perhaps you've created one virtualenv for both Python 2 and 3 (it wouldn't work), or are using a wrong PYTHONPATH.

Comments