I have a unit test that is passing when I run it via python manage.py test, but failing when I run it from within PyCharm.
def test_alpha(self):
from selenium.webdriver.common.utils import free_port
from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=PHANTOMJS_PATH, port=free_port())
driver.quit()
The exception I get when running from PyCharm is
WebDriverException: Message: 'Can not connect to GhostDriver'
I've spent a fair amount of time digging into this problem, and I've noticed that when I specify a port manually the test passes within PyCharm.
# suppose 50000 happens to be a free port on your computer
driver = webdriver.PhantomJS(executable_path=PHANTOMJS_PATH, port=50000)
To quickly recap:
Test passes with python manage.py test
Test passes in PyCharm if port is specified manually
Test fails in PyCharm if port=free_port()
What is PyCharm doing that is making the test unable to connect to Ghostdriver?
# For convenience, the `free_port()` code snippet is here
# selenium.webdriver.common.utils.freeport
def free_port():
free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
free_socket.bind(('127.0.0.1', 0))
free_socket.listen(5)
port = free_socket.getsockname()[1]
free_socket.close()
return port
Something in your terminal setup probably influences the networking.
Try to start PyCharm from your terminal:
open -a /Applications/PyCharm.app/
Then run the test again, and it should pass.
Source: sum-up of #CrazyCoder's comments
Try installing phantomjs with npm:
https://www.npmjs.com/package/phantomjs.
I use Mac OS X and I had a similar issue using by selenium and django.
Related
Running RPi4s with Ubuntu Server 19.10, Python 3.7.5, python3-xlib==0.15 and pyautogui==0.9.50. Everything is run as the default ubuntu user.
I'm trying to have Machine A send an ssh command to Machine B to run a GUI program and do some processing. I'm getting some XAUTHORITY errors.
Note: I don't want to see the GUI on Machine As monitor - but the app running on Machine B needs a GUI.
So on Machine A I run:
subprocess.Popen(['ssh', 'ubuntu#ip_of_machine_B', 'python3', '/path/to/my_script.py'])
On Machine B, my_script.py executes
subprocess.call(['python3', '/path/to/gui_script.py'])
Finally, gui_script.py attempts to
import os
os.environ['DISPLAY'] = ':0'
os.environ['XAUTHORITY'] = '/run/user/1000/gdm/Xauthority'
import subprocess
import pyautogui
subprocess.Popen(['the_gui_app'])
# Do stuff with pyautogui and the app.
Unfortunately, gui_script.py is throwing the following
Xlib.error.DisplayConnectionError: Can't connect to display ":0": No protocol specified.
I also tried setting the environment in the subprocess call in my_script.py via
my_env = os.environ.copy()
my_env['DISPLAY'] = ':0'
my_env['XAUTHORITY'] = '/run/user/1000/gdm/Xauthority'
subprocess.call(['python3', '/path/to/gui_script.py'], env=my_env)
But that also failed.
My best guess is I need to change some setting somewhere on Machine B prior to running the workflow (ie, a one-time edit to xauth)? This is a closed system so security isn't an issue!
My environments are based on windows with vagrant or docker as the actual environments. I'd like to set up a quick way of ad hoc deploying stuff directly from windows though, it would be great if I could just run
fab deploySomething
And that would for example locally build an react app, commit and push to the server. However I'm stuck at the local bit.
My setup is:
Windows 10
Fabric 2
Python 3
I've got a fabfile.py set up with a simple test:
from fabric import Connection, task, Config
#task
def deployApp(context):
config = Config(overrides={'user': 'XXX', 'connect_kwargs': {'password': 'YYY'}})
c = Connection('123.123.123.123', config=config)
# c.local('echo ---------- test from local')
with c.cd('../../app/some-app'):
c.local('dir') #this is correct
c.local('yarn install', echo=True)
But I'm just getting:
'yarn' is not recognized as an internal or external command, operable program or batch file.
you can replace 'yarn' with pretty much anything, I can't run a command with local that works fine manually. With debugging on, all i get is:
DEBUG:invoke:Received a possibly-skippable exception: <UnexpectedExit: cmd='cd ../../app/some-app && yarn install' exited=1>
which isn't very helpful...anyone came across this? Any examples of local commands with fabric I can find seem to refer to the old 1.X versions
To run local commands, run them off of your context and not your connection. n.b., this drops you to the invoke level:
from fabric import task
#task
def hello(context):
with context.cd('/path/to/local_dir'):
context.run('ls -la')
That said, the issue is probably that you need the fully qualified path to yarn since your environment's path hasn't been sourced.
I got this error message sublime issue(My OS: Ubuntu 16.04) "socket.error: [Errno 98] Address already in use" If I run flask in sublime text or PyCharm. But if I run flask on my Ubuntu terminal,it is running. I understood that port used another service. Then i was trying to solve this issue from google/stackoverflow.
# ps ax | grep 5000 // or # ps ax | grep name_of_service
# kill 3750 // or # killall name_of_service
But nothing changed. Only i found this problem when i was trying to run on sublime or pycharm IDE.
Simple way is to use fuser.
fuser <yourport>/tcp #this will fetch the process/service
Replace <yourport> with the port you want to use
#to kill the process using <yourport> add `-k` argument
fuser <yourport>/tcp -k
In your case
fuser 5000/tcp -k
Now you can run flask with that port.
Pycharm allows you to edit the run configuration, so enter the configuration and check the box (top-right corner) saying: "singleton instance". In this way, every time you restart the server, the previous connection on port 5000 is closed and opened again.
I'm trying to run PhantomJS from within selenium.webdriver on a Centos server. PhantomJS is in the path and is running properly from terminal. However in the script it appears to be launched, but afterwards cannot be reached on the specified port (I tried 2 different opened ports from my provider 29842 and 60099, they both are not working and neither launching it without a specified port).
The error happens here in selenium.webdriver.common.utils:
try:
socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_.settimeout(1)
socket_.connect(("localhost", port))
socket_.close()
return True
except socket.error:
return False
This is from my script (I tried without any parameters as well as writing the complete path to the executable and neither worked):
self.browser = webdriver.PhantomJS(
port=29842,
desired_capabilities={
'javascriptEnabled': True,
'platform': 'windows',
'browserName': 'Mozilla',
'version': '5.0',
'phantomjs.page.settings.userAgent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
}
)
And this the script that initialises the webdriver from selenium.webdriver.phantomjs.service. I checked and subprocess.Popen actually lauches phantomjs, the error happens in the while loop:
try:
self.process = subprocess.Popen(self.service_args,
stdout=self._log, stderr=self._log)
except Exception as e:
raise WebDriverException("Unable to start phantomjs with ghostdriver.", e)
count = 0
while not utils.is_connectable(self.port):
print utils.is_connectable(self.port)
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can not connect to GhostDriver")
All the packages are the latest version: python 2.7, selenium 2 and phantomjs 1.9 binary with ghostdriver integrated. I made the same script work properly on my Ubuntu local machine, doing exactly the same things I did on the server. What is different on the server?
I had this issue on Ubuntu after upgrading to a new version. I re-installed all of the nodejs and python packages, but what I think solved the issue was making sure the nodejs executable was symbolically linked to node.
These are the commands I used:
apt-get remove node nodejs
apt-get install build-essential python-dev phantomjs npm nodejs
ln -s /usr/bin/nodejs /usr/bin/node
npm install -g phantomjs
pip install selenium bson BeautifulSoup pymongo
Installing nodejs-legacy package on Linux Mint 14 solved this for me.
sudo apt-get install nodejs-legacy
For me, this was a firewall issue. Phantom requires an open port to connect. If the port is blocked by a firewall, you'll get WebDriverException("Can not connect to GhostDriver").
To fix:
Open a port.
sudo iptables -A INPUT -s 127.0.0.1 -p tcp --dport 65000 -j ACCEPT
Create a PhantomJS driver that uses that port
driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs', port=65000)
I had this problem and found out what was causing it. In another tutorial on developing Facebook applications, I was told to nano in to /etc/hosts and change it from this-
127.0.0.1 localhost
to this-
127.0.0.1 test1.com
and save the file. Incidentally, PhantomJS() was not working anymore after that. I just went back in to the /etc/hosts file and switched it back to localhost
127.0.0.1 localhost
and it works again.
I am testing a python/django application using selenium with phantomjs. Everything worked fine during first (and sometimes second test), but once running the next test, selenium printed the exact same error message.
Furthermore, if I ran phantomjs from console afterwards, I received the following node error:
child_process.js:1136 var err = this._handle.spawn(options);
^
TypeError: Bad argument
at TypeError (native)
at ChildProcess.spawn (child_process.js:1136:26)
at exports.spawn (child_process.js:995:9)
at Object.<anonymous> (/usr/local/lib/node_modules/phantomjs/bin/phantomjs:22:10)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:320)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
I tried reinstalling phantomjs via npm (both locally and globally) several times, but the behaviour persisted.
Eventually, I uninstalled phantomjs via npm and downloaded the phantomjs bin from phantomjs.org instead. Put that inside my /usr/local/bin (I am on MacOS) and got rid of the error since!
I am trying to run a simple hello world example in python that runs against mongodb. I've set up mongo, bottle and pymong and have the following script inside C:\Python27\Scripts:
import bottle
import pymongo
#bottle.route('/')
def index()
from pymongo import Connection
connection = Connection('localhost', 27017)
db = connection.test
names = db.names
item = names.find_one()
return '<b>Hello %s!</b>' % item['name']
bottle.run(host='localhost', port=8082)
-!-- hello.py All L8 (Python)
I want to run this locally and I go to http://localhost:8082 but I get not found not found. How can I run that code to test it locally on my computer so I can test the code via the browser. I am running Windows 7 and have WAMP installed.
1) Add : after function name:
def index():
2) WAMP does not include MongoDB. You need to install Mongodb locally as well.
3) If something doesn't work, then you generally should be looking console for errors.
This script will run standalone (bottle.run() starts its own Python webserver), so you do not need any WAMP - just run this script. Run it from command line so you see if there are any errors.
You also need to have running MongoDB to connect to it. You can run it from command line too if you do not have MongoDB configured to start automatically after Windows start.