I have seen simple code in stackoverflow using pyserial in USB ports with Python 3.3 but I can't get this to work on my new installation of pyserial 2.7 [in Windows 7, 64 bit, with 3 USB ports]. Installation of pyserial went smoothly, I can import without error and methods are recognized in the Pyscripter IDE which boosts confidence in a good installation, however:
The code stripped down to its error producing essentials is:
import serial
def main():
ser = serial.Serial(port='COM2')
ser.close()
if __name__ == '__main__':
main
From this I receive a dialog box with the error "SerialException: could not open port 'COM2': FileNotFoundError(2,'The system cannot find the file specified.',None,2)"
The Traceback states:
*** Remote Interpreter Reinitialized ***
>>>
Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "C:\Python33\Lib\site-packages\scanport2.py", line 19, in <module>
main()
File "C:\Python33\Lib\site-packages\scanport2.py", line 15, in main
ser = serial.Serial(port='COM2')
File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python33\Lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
File "C:\Python33\Lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM2': FileNotFoundError(2, 'The system cannot find the file specified.', None, 2)
And the code segment in the imported module which raises the SerialException is:
# the "\\.\COMx" format is required for devices other than COM1-COM8
# not all versions of windows seem to support this properly
# so that the first few ports are used with the DOS device name
port = self.portstr
try:
if port.upper().startswith('COM') and int(port[3:]) > 8:
port = '\\\\.\\' + port
except ValueError:
# for like COMnotanumber
pass
self.hComPort = win32.CreateFile(port,
win32.GENERIC_READ | win32.GENERIC_WRITE,
0, # exclusive access
None, # no security
win32.OPEN_EXISTING,
win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
0)
if self.hComPort == win32.INVALID_HANDLE_VALUE:
self.hComPort = None # 'cause __del__ is called anyway
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
I do have an active device connected to COM2 as identified in the Windows device manager. I also have tried scanning all the ports, but the code stops on the first use of serial.Serial
This appears that something may be going on with win32?
I am a newbie for interfacing Python with hardware.
I would try the following:
Unplug and replug the device.
Reboot.
Run WinObj and look in the GLOBAL?? folder; you should see COM2 there as a symbolic link to something more driver-specific.
What type of device do you have connected to COM2? If it uses usbser.sys, you might have better luck substituting \\.\USBSER000 for COM2 in your code, but remember to escape those backslashes properly.
On some machines there are strange problems with low COM port numbers that I can't explain. Try reassigning the device to COM6 in the Device Manager.
It looks like the pyserial download page only contains links for 32 bit python? This unofficial page seems to have links for 64 bit installations, however be cautious installing from unknown sources.
This answer also suggests installing it using pip: https://stackoverflow.com/a/8491164/66349
Related
I am using python 3's module tftpy to attempt to handle tftp style downloading of a file. However, when I run the application I get the following error:
\Python38\site-packages\tftpy\TftpStates.py", line 53, in handleOACK
raise TftpException("No options found in OACK")
tftpy.TftpShared.TftpException: No options found in OACK
How do I get my python project to ignore OACK/ send a new request packet that doesn't include an OACK?
Disclaimer: This is my first time attempting to work with TFTP packets so I am fairly new. If the question I posed isn't the appropriate way to handle it, what should I be doing?
MORE DATA ON THE PROBLEM:
I am using an external chip that is programmed to ignore OACK packet options.
When I used C# and the TFTP.Net package the transfer worked, so I don't believe it is an issue with my TFTP server. However, as our main application is based in python I want to be able to handle this communication via python 3.
I am running python 3.8.5
On my server side it is saying it receives a packet with error code 8.
python Script:
import tftpy
client = tftpy.TftpClient('192.168.0.42', 69)
client.download('triplog.txt', 'faultlog.txt', packethook=None, timeout=5)
full traceback:
Failed to negotiate options: No options found in OACK
Traceback (most recent call last):
File "C:\Users\selena\Documents\PythonScripts\TFTP\TFTPTestScript.py", line 23, in <module>
client.download('triplog.txt', 'faultlog.txt', packethook=None, timeout=5)
File "C:\Users\selena\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\tftpy\TftpClient.py", line 58, in download
self.context.start()
File "C:\Users\selena\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\tftpy\TftpContexts.py", line 402, in start
self.cycle()
File "C:\Users\selena\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\tftpy\TftpContexts.py", line 202, in cycle
self.state = self.state.handle(recvpkt, raddress, rport)
File "C:\Users\selena\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\tftpy\TftpStates.py", line 566, in handle
self.handleOACK(pkt)
File "C:\Users\selena\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\tftpy\TftpStates.py", line 53, in handleOACK
raise TftpException("No options found in OACK")
tftpy.TftpShared.TftpException: No options found in OACK
[Finished in 0.7s with exit code 1]
Credit #ewong for this workaround solution
The code worked after adding in options when initializing the client even though I didn't need them. I'll be filing an issue #https://github.com/msoulier/tftpy to see if this is a bug that needs to be addressed or a deliberate choice.
Solution code:
import tftpy
client = tftpy.TftpClient('192.168.0.42', 69, options={'blksize': 8})
client.download('triplog.txt', 'faultlog.txt', packethook=None, timeout=5)
I have a USB device which I'm tring to talk to using pyusb 1.0.2 on linux (Linux tpad 4.15.0-38-generic #41~16.04.1-Ubuntu SMP Wed Oct 10 20:16:04 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux). Running python 3.5 I get the following error (full trace at bottom of this post):
usb.core.USBError: [Errno 13] Access denied (insufficient permissions)
Mounting the usb and using lsusb and then inspecting it:
udevadm info -a -p $(udevadm info -q path -n /dev/bus/usb/006/011)
shows
looking at device '/devices/pci0000:00/0000:00:10.0/usb6/6-1':
KERNEL=="6-1"
SUBSYSTEM=="usb"
DRIVER=="usb"
ATTR{authorized}=="1"
ATTR{avoid_reset_quirk}=="0"
ATTR{bConfigurationValue}=="1"
ATTR{bDeviceClass}=="00"
ATTR{bDeviceProtocol}=="00"
ATTR{bDeviceSubClass}=="00"
ATTR{bMaxPacketSize0}=="8"
ATTR{bMaxPower}=="98mA"
ATTR{bNumConfigurations}=="1"
ATTR{bNumInterfaces}==" 1"
ATTR{bcdDevice}=="0111"
ATTR{bmAttributes}=="80"
ATTR{busnum}=="6"
ATTR{configuration}==""
ATTR{devnum}=="11"
ATTR{devpath}=="1"
ATTR{idProduct}=="0001"
ATTR{idVendor}=="17a4"
ATTR{ltm_capable}=="no"
ATTR{manufacturer}=="Concept2"
ATTR{maxchild}=="0"
ATTR{product}=="Concept2 Performance Monitor 3 (PM3)"
ATTR{quirks}=="0x0"
ATTR{removable}=="unknown"
ATTR{serial}=="300118412"
ATTR{speed}=="12"
ATTR{urbnum}=="12"
ATTR{version}==" 1.10"
So I wrote a rule in /etc/udev/rules.d/10-local.rules like this (FYI -- I've also tried "user1" which is the user python shows it is running under and I've tried both ":=" and "="):
SUBSYSTEMS=="usb", ATTRS{idVendor}=="17a4", ATTRS{idProduct}=="0001", GROUP:="users", MODE="0777"
Then I ran udevadm test /devices/pci0000:00/0000:00:10.0/usb6/6-1
which shows:
calling: test
version 229
This program is for debugging only, it does not run any program
specified by a RUN key. It may show incorrect results, because
some values may be different, or not available at a simulation run.
=== trie on-disk ===
tool version: 229
file size: 7049340 bytes
header size 80 bytes
strings 1759644 bytes
nodes 5289616 bytes
Load module index
timestamp of '/etc/systemd/network' changed
timestamp of '/lib/systemd/network' changed
Parsed configuration file /lib/systemd/network/99-default.link
Created link configuration context.
timestamp of '/etc/udev/rules.d' changed
Reading rules file: /etc/udev/rules.d/10-local.rules
Reading rules file: /lib/udev/rules.d/40-crda.rules
[removed long list of rule files...]
Skipping empty file: /etc/udev/rules.d/99-usbftdi.rules
rules contain 393216 bytes tokens (32768 * 12 bytes), 33403 bytes strings
25688 strings (211409 bytes), 22263 de-duplicated (181432 bytes), 3426 trie nodes used
GROUP 100 /etc/udev/rules.d/10-local.rules:1
MODE 0777 /etc/udev/rules.d/10-local.rules:1
value '[dmi/id]sys_vendor' is 'LENOVO'
value '[dmi/id]sys_vendor' is 'LENOVO'
IMPORT builtin 'usb_id' /lib/udev/rules.d/50-udev-default.rules:13
IMPORT builtin 'hwdb' /lib/udev/rules.d/50-udev-default.rules:13
MODE 0664 /lib/udev/rules.d/50-udev-default.rules:41
PROGRAM 'mtp-probe /sys/devices/pci0000:00/0000:00:10.0/usb6/6-1 6 11' /lib/udev/rules.d/69-libmtp.rules:1923
starting 'mtp-probe /sys/devices/pci0000:00/0000:00:10.0/usb6/6-1 6 11'
'mtp-probe /sys/devices/pci0000:00/0000:00:10.0/usb6/6-1 6 11'(out) '0'
Process 'mtp-probe /sys/devices/pci0000:00/0000:00:10.0/usb6/6-1 6 11' succeeded.
handling device node '/dev/bus/usb/006/011', devnum=c189:650, mode=0664, uid=0, gid=100
set permissions /dev/bus/usb/006/011, 020664, uid=0, gid=100
setting mode of /dev/bus/usb/006/011 to 020664 failed: Operation not permitted
setting owner of /dev/bus/usb/006/011 to uid=0, gid=100 failed: Operation not permitted
ACTION=add
BUSNUM=006
DEVNAME=/dev/bus/usb/006/011
DEVNUM=011
DEVPATH=/devices/pci0000:00/0000:00:10.0/usb6/6-1
DEVTYPE=usb_device
DRIVER=usb
ID_BUS=usb
ID_MODEL=Concept2_Performance_Monitor_3__PM3_
ID_MODEL_ENC=Concept2\x20Performance\x20Monitor\x203\x20\x28PM3\x29
ID_MODEL_FROM_DATABASE=Performance Monitor 3
ID_MODEL_ID=0001
ID_REVISION=0111
ID_SERIAL=Concept2_Concept2_Performance_Monitor_3__PM3__300118412
ID_SERIAL_SHORT=300118412
ID_USB_INTERFACES=:030000:
ID_VENDOR=Concept2
ID_VENDOR_ENC=Concept2
ID_VENDOR_FROM_DATABASE=Concept2
ID_VENDOR_ID=17a4
MAJOR=189
MINOR=650
PRODUCT=17a4/1/111
SUBSYSTEM=usb
TYPE=0/0/0
USEC_INITIALIZED=3850171749
Unload module index
Unloaded link configuration context.
However after doing this python still reports access errors to the USB device.
Traceback (most recent call last):
File "/home/user1/PycharmProjects/PyRow/statshow.py", line 22, in <module>
erg = pyrow.pyrow(ergs[0])
File "/home/user1/PycharmProjects/PyRow/pyrow.py", line 61, in __init__
usb.util.claim_interface(erg, INTERFACE)
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/util.py", line 205, in claim_interface
device._ctx.managed_claim_interface(device, interface)
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/core.py", line 159, in managed_claim_interface
self.managed_open()
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/core.py", line 120, in managed_open
self.handle = self.backend.open_device(self.dev)
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/backend/libusb1.py", line 786, in open_device
return _DeviceHandle(dev)
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/backend/libusb1.py", line 643, in __init__
_check(_lib.libusb_open(self.devid, byref(self.handle)))
File "/home/user1/PycharmProjects/camera/venv/lib/python3.5/site-packages/usb/backend/libusb1.py", line 595, in _check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 13] Access denied (insufficient permissions)
I'm out of ideas on how to fix this. Are there any suggestions?
Using this answer I found I could correct the permissions problem using the plugdev group.
So in a terminal I used
groups
groups [myuserid]
and verified plugdev was there and the user was part of that group. Then I put the following line in /etc/udev/rules.d/10-local.rules
SUBSYSTEMS=="usb", ENV{DEVTYPE}=="usb_device",
ATTRS{idVendor}=="17a4", ATTRS{idProduct}=="0001", GROUP="plugdev",
MODE="0777"
I'm not sure if the devtype and if 0777 or 0666 is proper, but this is what worked.
After making the changes I also ran the following commands to reset the rules for the system:
sudo udevadm control --reload
sudo udevadm trigger
given that this is the first result on google, and that i don't see the answer that fixed this issue for me, I figured i'd post.
the udev rules do not allow comments and seems to fail pretty much silently, so if you tried adding comments to keep track of your devices, you'll have broken the permissions for those devices.
SUBSYSTEMS=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="faf0", GROUP="plugdev", MODE="0777"
will work, but
SUBSYSTEMS=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="faf0", GROUP="plugdev", MODE="0777" # thorlabs KB101 motor controller
will not
I am able to run scripts with Python 2.6.6 that open the serial port and exchange data bidirectionally. After installing both Python 2.7 and 3.5, needed for objects that cannot be executed in 2.6, I receive the same error (IOError: [Errno 110] Connection timed out).
I installed both 2.7 and 3.5 using (make altinstall) followed by (easy_install-2.7 -U pyserial) and (easy_install-3.5 -U pyserial).
Does anyone have a good guess as to why 2.6 will open the port and pass data, but both 2.7 and 3.5 fail?
I am running on CentOS 6.8, Kernel Linux 2.6.32-642.11.1.el6.x86_64 and using a USB to DB9 serial cable without any issues in 2.6.
python stest.py
Hello World from serial port running under Python 2.6.6.
python2.7 stest.py
Traceback (most recent call last):
File "stest.py", line 3, in <module>
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=False,dsrdtr=False)
File "build/bdist.linux-x86_64/egg/serial/serialutil.py", line 182, in __init__
File "build/bdist.linux-x86_64/egg/serial/serialposix.py", line 267, in open
File "build/bdist.linux-x86_64/egg/serial/serialposix.py", line 588, in _update_rts_state
IOError: [Errno 110] Connection timed out
python3.5 stest.py
Traceback (most recent call last):
File "stest.py", line 3, in <module>
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=False,dsrdtr=False)
File "/usr/local/lib/python3.5/site-packages/pyserial-3.2.1-py3.5.egg/serial/serialutil.py", line 236, in __init__
File "/usr/local/lib/python3.5/site-packages/pyserial-3.2.1-py3.5.egg/serial/serialposix.py", line 288, in open
File "/usr/local/lib/python3.5/site-packages/pyserial-3.2.1-py3.5.egg/serial/serialposix.py", line 605, in _update_rts_state
TimeoutError: [Errno 110] Connection timed out
The stest.py script:
import serial
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=False,dsrdtr=False)
ser.write("Hello from CentOS box.");
while True:
chunk = ser.read(128)
if(chunk != ''):
print(chunk + '\n')
ser.close()
As suggested earlier, I did try to open the port several times. I had read that may be an issue from other posts. I also increased the timeout from 0 to 5. Still no joy. Here is that version (assuming I understood the way to make the multiple attempts):
import serial
ser = 0
for i in range (1, 20):
print("Attempt" + str(i))
try:
ser = serial.Serial(port='/dev/ttyUSB0',timeout=5,xonxoff=False,rtscts=False,dsrdtr=False)
if(ser):
break
except:
print("Failed")
ser.write("Hello from CentOS");
while True:
chunk = ser.read(24)
if(chunk != ''):
print(chunk + '\n')
ser.close()
I think this may be kernel related. I was able to exchange data by changing the rtscts value from False to 1. Unfortunately, this does not help my end goal since the remote device is 3-wire and does not support handshaking (RTS/CTS). So, I am still without a solution. The question now is:
Why does the (rtscts value of False) fail in 2.7 and 3.5, but work in 2.6.6?
The working code (but not usable to me because my equip does not handshake):
#!/usr/bin/python3.5
import serial
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=1,dsrdtr=False)
ser.write(b"Hello from CentOS");
while True:
chunk = ser.read(24)
if(chunk):
print(str(chunk) + '\n')
ser.close()
Adding to the evolution of my discovery, it is indeed an issue in the compatibility of CentOS 6.8 and pyserial's serialutil.py and serialposix.py. I can open a serial port and read/write data just fine with rtscts = 1. If I reconfigure the port during run time and set rtscts to False, 2.6.6 handles it well. Pythons 2.7 and 3.5 immediately issue errors and abort displaying the same ([Errno 110]) error shown at the beginning of my post. Here is the code if others would care to replicate. Preferably CentOS users since this is likely OS related.
import serial
ser = serial.Serial(port='/dev/ttyUSB0',timeout=0,xonxoff=False,rtscts=1,dsrdtr=False)
# Python 2.6.6, 2.7, and 3.5 will send this following string.
ser.write(b"Hello from CentOS");
# Python 2.7 and 3.5 error-out after this change, but system Python (2.6.6) is okay.
ser.rts = False
while True:
chunk = ser.read(24)
if(chunk):
print(str(chunk) + '\n')
ser.close()
Any suggestions on next steps? Am I just out of luck?
I am trying to implement data sending in Python 3 on a raspberryPi (as a part of a bigger project) and cannot receive data when I connect the Rx and Tx pins. Regardless of using Python 2 or 3 (as far as I understand this API allows Python 3 programming) I either get Received: b'\n' response or such an exception:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 471, in write
n = os.write(self.fd, d)
OSError: [Errno 5] Input/output error
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./uart.py", line 12, in <module>
port.write(bytearray(input_data, 'utf-8'))
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 485, in write
raise SerialException('write failed: %s' % (v,))
serial.serialutil.SerialException: write failed: [Errno 5] Input/output error
I can't write anything except from buffered reader though.
The code I've made is here:
#!/usr/bin/env python3
import serial
port = serial.Serial("/dev/ttyAMA0", baudrate=9600)
while True:
input_data = input("Say sth: ")
if input_data != 'exit':
port.write(bytearray(input_data, 'utf-8'))
print('Sent: {0}'.format(bytearray(input_data, 'ASCII')))
output_data = port.readline()
print('Received: {0}\n'.format(str(output_data)))
else:
break
port.close()
I want to use ASCII encoding since it will be further connected to an microcontroller with code in C. I've also checked whether any data is written into the buffer (and it is), I've tried out laying the programme to sleep for a second after sending data, I've tried using port.read(port.inWaiting()) and port.read(in_waiting) (no attribute found in the latter case) and nothing seems to be helpful.
I've also tried this example; I am sure correct pins are connected and I have updated and upgraded my raspbian by using sudo apt-get update and sudo apt-get upgrade and when I typed sudo apt-get install python3-serial I was told that I already have newest version installed.
I am posting this answear to close the topic and to help anyone who might come across similar difficulties.
Since the processor is of different architecture trying to set up ports with setserial was pointles, however this was exactly the problem.
pi#raspberrypi ~ $ sudo setserial -g /dev/ttyAMA0
/dev/ttyAMA0, UART: undefined, Port: 0x0000, IRQ: 83
The answear I found here solved all the problems.
I'm running Pycharm 4.5.3 on OS X Yosemite (10.10.3). I created a simple python program, and tried opening the python console, and got this stack trace error:
/usr/bin/python -u /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py 59286 59287
Error starting server with host: localhost, port: 59286, client_port: 59287
Unhandled exception in thread started by <function start_server at 0x100d9bd70>
Traceback (most recent call last):
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py", line 283, in start_server
server = XMLRPCServer((host, port), logRequests=False, allow_none=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SimpleXMLRPCServer.py", line 593, in __init__
SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 419, in __init__
self.server_bind()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 430, in server_bind
self.socket.bind(self.server_address)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
Couldn't connect to console process.
A similar question was raised here on stack overflow, but the root of the error was the string localhost passed in with white spaces, which is not the case here (host has been assigned to 'localhost'). Does anyone have any idea? This isn't really a big deal, seeing as I can use python command line in terminal, but I'm curious if this is a bug within Pycharm.
Edit: here's the source code to the Pycharm script.
if __name__ == '__main__':
import pydevconsole
sys.stdin = pydevconsole.BaseStdIn()
port, client_port = sys.argv[1:3]
import pydev_localhost
if int(port) == 0 and int(client_port) == 0:
(h, p) = pydev_localhost.get_socket_name()
client_port = p
pydevconsole.StartServer(pydev_localhost.get_localhost(), int(port), int(client_port))
The answers given so far do not get at the underlying cause, which is likely to be that your OS X /etc/hosts file does not contain an entry for: 127.0.0.1 localhost
Update the hosts file with the line:
127.0.0.1 localhost
(you will need to use sudo), then restart pyCharm. Unless you know what you are doing, editing your IDE source code is not a good idea.
I'm new in python, stuck on the same problem for half a day. Finally solved this problem by setting the host to 127.0.0.1.
If you have the same issue you can do this by:
open pydevconsole.py in pycharm, navigate to the main script part and find this line:
pydevconsole.StartServer(pydev_localhost.get_localhost(), int(port), int(client_port))
ctrl + click the function get_localhost() to navigate to its source:
_cache = None def get_localhost():'''
Should return 127.0.0.1 in ipv4 and ::1 in ipv6
localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work
properly and takes a lot of time (had this issue on the pyunit server).
Using the IP directly solves the problem.
'''
#TODO: Needs better investigation!
global _cache
if _cache is None:
try:
for addr_info in socket.getaddrinfo("localhost", 80, 0, 0, socket.SOL_TCP):
config = addr_info[4]
if config[0] == '127.0.0.1':
_cache = '127.0.0.1'
return _cache
except:
#Ok, some versions of Python don't have getaddrinfo or SOL_TCP... Just consider it 127.0.0.1 in this case.
_cache = '127.0.0.1'
else:
_cache = 'localhost'
return _cache
I believe the problem is caused by the returning "localhost" of this function, make it "127.0.0.1" solved the problem.
I had this issue on OS X El Capitan, running Pycharm 2016.2.
In any editor open: /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py
If you're navigating via Finder, right-click the Pycharm.app file and choose "Show Package Contents" to get access to the path.
Find the line:
pydevconsole.start_server(pydev_localhost.get_localhost(), int(port), int(client_port))
Change it to:
pydevconsole.start_server('127.0.0.1', int(port), int(client_port))
Restart Pycharm and choose Tools->Python Console...
You should then see:
Users/.../env/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py 56582 56583
PyDev console: starting.
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['/Users/...'])
Python 3.5.0 (default, Dec 1 2015, 12:50:23)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)] on darwin