Setting up Chrome DevTools (Selenium 4) Using Remote WebDriver in Python - asynchronous

I've been trying to set up the use of the Chrome DevTools using Selenium 4 and Python. I've been able to get it to run locally (without any of the async stuff), but when I try to use the webdriver.Remote implementation, it crashes.
Here is an example from the Selenium docs: https://www.selenium.dev/de/documentation/support_packages/chrome_devtools/
Below is how I tried to run it.
import asyncio
from selenium import webdriver
import selenium.webdriver.common.devtools.v96 as devtools
async def geo_location_test():
try:
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Remote(
command_executor='http://D5365900:4444/wd/hub',
options=chrome_options
)
async with driver.bidi_connection() as session:
cdp_session = session.session
await cdp_session.execute(devtools.emulation.set_geolocation_override(latitude=41.8781,
longitude=-87.6298,
accuracy=100))
driver.get("https://my-location.org/")
finally:
driver.quit()
async def main():
await geo_location_test()
if __name__ == "__main__":
asyncio.run(main())
It runs up to the line async with driver.bidi_connection() as session: (session is established and Chrome browser opens). But the it crashes with the following trace.
Traceback (most recent call last):
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 54, in <module>
asyncio.run(main())
File "C:\Program Files\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
return future.result()
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 51, in main
await geo_location_test()
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 40, in geo_location_test
async with driver.bidi_connection() as session:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1576, in bidi_connection
async with cdp.open_cdp(ws_url) as conn:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 457, in open_cdp
async with trio.open_nursery() as nursery:
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 796, in __aenter__
self._scope.__enter__()
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_ki.py", line 159, in wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 449, in __enter__
task = _core.current_task()
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 2285, in current_task
raise RuntimeError("must be called from async context") from None
RuntimeError: must be called from async context
As you can see, I'm using Python 3.10. I also upgraded the Selenium bindings to 4.1.0 and am running a Selenium 4.0.0 Hub/Node config to automate Chrome 96.
Any ideas, what is the problem here? Am I handling the asynchronous coroutines incorrectly?
Any help is much appreciated!
Update
After trying to run it with trio (as suggested in Henry Ashton-Martyn's comment), I get the following error.
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\site-packages\trio\_highlevel_open_tcp_stream.py", line 332, in attempt_connect
await sock.connect(sockaddr)
File "C:\Program Files\Python310\lib\site-packages\trio\_socket.py", line 682, in connect
raise OSError(err, "Error in connect: " + os.strerror(err))
OSError: [Errno 10049] Error in connect: Unknown error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 58, in <module>
trio.run(main)
File "C:\Program Files\Python310\lib\site-packages\trio\_core\_run.py", line 1932, in run
raise runner.main_task_outcome.error
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 55, in main
await geo_location_test()
File "C:\Users\y04082\eclipse-workspace\WWI-Testautomation\TestScripts\Josh\async_sel_4.py", line 44, in geo_location_test
async with driver.bidi_connection() as session:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1576, in bidi_connection
async with cdp.open_cdp(ws_url) as conn:
File "C:\Program Files\Python310\lib\contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 458, in open_cdp
conn = await connect_cdp(nursery, url)
File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\common\bidi\cdp.py", line 479, in connect_cdp
ws = await connect_websocket_url(nursery, url,
File "C:\Program Files\Python310\lib\site-packages\trio_websocket\_impl.py", line 262, in connect_websocket_url
return await connect_websocket(nursery, host, port, resource,
File "C:\Program Files\Python310\lib\site-packages\trio_websocket\_impl.py", line 171, in connect_websocket
stream = await trio.open_tcp_stream(host, port)
File "C:\Program Files\Python310\lib\site-packages\trio\_highlevel_open_tcp_stream.py", line 367, in open_tcp_stream
raise OSError(msg) from trio.MultiError(oserrors)
OSError: all attempts to connect to 0.0.0.0:4444 failed

It seems that selenium doesn't use python's builtin async framework but uses a package called trio as well. You should be able to fix this problem by changing this code from:
if __name__ == "__main__":
asyncio.run(main())
to:
if __name__ == "__main__":
import trio
trio.run(main)

Related

Python Executable including multiple libraries

I am relatively new to Python and have developed an application for myself that I would like to make an executable. It uses multiple external libraries such as Pyqt5, sqlite3, and openpyxl. I am using pyinstaller to create the .exe - the installer fails with a message "nomodulefound xml.parser.expat" i've tried a few ways to include it in my package but to no avail.
here is a replicable py example:
from decimal import Decimal
import openpyxl # xl libraries
wb = openpyxl.load_workbook(r'C:\Users\jmstr\OneDrive\Documents\finproxlc.xlsx')
myint = Decimal("27")
print("hello")
any ideas?
Here is my pyinstaller cmd: pyinstaller C:\Users\usr1\IdeaProjects\GUIProjects\finpro.py -p C:\Users\usr1\venv\Lib\site-packages\openpyxl --hidden-import openpyxl --additional-hooks-dir C:\Users\usr1\venv\Lib\site-packages\openpyxl --collect-all xml.parsers.expat
Output of the pyinstall:
['C:\Users\usr1\IdeaProjects\GUIProjects', 'C:\Users\usr1\venv\Lib\site-packages\openpyxl'] Traceback (most recent call last): File "c:\users\usr1\appdata\local\programs\python\python39\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "c:\users\usr1\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\usr1\AppData\Local\Programs\Python\Python39\Scripts\pyinstaller.exe_main.py", line 7, in File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller_main.py", line 194, in console_script_run run() File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller_main.py", line 180, in run run_build(pyi_config, spec_file, **vars(args)) File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller_main.py", line 61, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\building\build_main.py", line 977, in main build(specfile, distpath, workpath, clean_build) File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\building\build_main.py", line 899, in build exec(code, spec_namespace) File "C:\Users\usr1\finpro.spec", line 14, in a = Analysis( File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\building\build_main.py", line 379, in init self.hookspath += discover_hook_directories() File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\isolated_parent.py", line 404, in wrapped return call(function, *args, **kwargs) File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\isolated_parent.py", line 373, in call return isolated.call(function, *args, **kwargs) File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\isolated_parent.py", line 311, in call raise RuntimeError(f"Child process call to {function.name}() failed with:\n" + output) RuntimeError: Child process call to discover_hook_directories() failed with: File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\isolated_child.py", line 63, in run_next_command output = function(*args, **kwargs) File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\building\build_main.py", line 107, in discover_hook_directories import pkg_resources File "c:\users\usr1\appdata\local\programs\python\python39\lib\site-packages\pkg_resources_init_.py", line 35, in import plistlib File "c:\users\usr1\appdata\local\programs\python\python39\lib\plistlib.py", line 61, in from xml.parsers.expat import ParserCreate ModuleNotFoundError: No module named 'xml.parsers'
Seems like the installion of openpyxl was specific to my IDE (intelliJ) and i could not figure out how to change the spec file to get it to pick up but running this command resolved the issue:
python -m pip install openpyxl

"SSHException('No existing session')" errors with python ncclient

I am working on the code below, and I got SSHException('No existing session') error
from ncclient import manager
with manager.connect(host="192.168.1.40", port=830, username="cisco", password="cisco", hostkey_verify=False, device_params={'name':'iosxr'}, ssh_config=True, allow_agent=False,look_for_keys=False, timeout=10) as nc_conn:
nc_config = nc_conn.get_config(source='running').data_xml
print (nc_config)
yapi#MacBook-Pro-3 iTel % python test01.py
Traceback (most recent call last):
File "/Users/yapi/Documents/Scripts/Non-GIT/Python/2023/iTel/test01.py", line 4, in
with manager.connect(host="192.168.1.40", port=830, username="abdul", password="cisco", hostkey_verify=False, device_params={'name':'iosxr'}, ssh_config=True, allow_agent=False,look_for_keys=False, timeout=10) as nc_conn:
File "/usr/local/lib/python3.9/site-packages/ncclient/manager.py", line 176, in connect
return connect_ssh(*args, **kwds)
File "/usr/local/lib/python3.9/site-packages/ncclient/manager.py", line 143, in connect_ssh
session.connect(*args, **kwds)
File "/usr/local/lib/python3.9/site-packages/ncclient/transport/ssh.py", line 364, in connect
self._auth(username, password, key_filenames, allow_agent, look_for_keys)
File "/usr/local/lib/python3.9/site-packages/ncclient/transport/ssh.py", line 480, in _auth
raise AuthenticationError(repr(saved_exception))
ncclient.transport.errors.AuthenticationError: SSHException('No existing session')
yapi#MacBook-Pro-3 iTel %
I have tried using different flags in connect function, but no luck

FastAPI internal server error Exception in ASGI application

I developed an API with FastAPI and when I run it in my conda Ubuntu enviroment, and try any function all runs perfectly. But, when I run it in my conda Windows enviroment the API runs okey but when I try the functoin, I get the internal server error message as output and in the terminal i can see the following error described below. Note, the code is the same in both enviroments
Also, the conexion in jupyter notebook(in the conda windows enviroment) to the node works fine as well as any function I run.
This is the conexion via jupyter, thath works fine in both enviroments:
rpc_user = os.getenv("u1")
rpc_password = os.getenv("key2")
rpc_host = os.getenv("host")
rpc_client = AuthServiceProxy(f"http://{rpc_user}:{rpc_password}#{rpc_host}", timeout=120)
block_count = rpc_client.getblockcount()
print("---------------------------------------------------------------")
print("Block Count:", block_count)
print("---------------------------------------------------------------\n")
output:
---------------------------------------------------------------
Block Count: 773863
---------------------------------------------------------------
This is the code for the connection in the API that it is in a directory named blockchain_data :
import os
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import json
client = os.getenv("u1")
key = os.getenv("key2")
host= os.getenv("host")
rpc_client = AuthServiceProxy(f"http://{client}:{key}#{host}", timeout=120)
This is the router for getblockcount, that works fine in my ubuntu enviroment but not in the windows.
from fastapi import APIRouter
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from blockchain_data.node import rpc_client
router = APIRouter()
#router.get("/get/block/count")
def get_block_count():
block_count = rpc_client.getblockcount()
return {"Last block":block_count}
And the main:
from fastapi import FastAPI
from routers import routers
app = FastAPI()
app.include_router(routers.router)
#app.get("/")
def inicio():
return{
"message": "welcome"
}
ERROR:
←[1mGET /get/block/count HTTP/1.1←[0m" ←[91m500 Internal Server Error←[0m
←[31mERROR←[0m: Exception in ASGI application
Traceback (most recent call last):
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 407, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\fastapi\applications.py", line 270, in __call__
await super().__call__(scope, receive, send)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
raise exc
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
raise exc
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
raise e
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\routing.py", line 706, in __call__
await route.handle(scope, receive, send)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\routing.py", line 276, in handle
await self.app(scope, receive, send)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\routing.py", line 66, in app
response = await func(request)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\fastapi\routing.py", line 237, in app
raw_response = await run_endpoint_function(
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\fastapi\routing.py", line 165, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\starlette\concurrency.py", line 41, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\anyio\to_thread.py", line 31, in run_sync
return await get_asynclib().run_sync_in_worker_thread(
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\anyio\_backends\_asyncio.py", line 937, in run_sync_in_worker_thread
return await future
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\anyio\_backends\_asyncio.py", line 867, in run
result = context.run(func, *args)
File ".\routers\routers.py", line 17, in get_block_count
block_count = rpc_client.getblockcount()
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\bitcoinrpc\authproxy.py", line 139, in __call__
response = self._get_response()
File "C:\Users\grupo\miniconda3\envs\entorno1\lib\site-packages\bitcoinrpc\authproxy.py", line 186, in _get_response
raise JSONRPCException({
bitcoinrpc.authproxy.JSONRPCException: -342: non-JSON HTTP response with '401 Unauthorized' from server
I tried to run the conexion with the node in jupter and works fine, it something related to FastAPI or uvicorn

AuthorizationFailed - "The client 'xxx' with object id 'xxx does not have authorization to perform action

I've tried to get Workspace from config which I do have access to, but it fails with the following error:
import azureml.core
print("SDK version:", azureml.core.VERSION)
from azureml.core.workspace import Workspace
ws = Workspace.from_config()
print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n')
SDK version: 0.1.80 Found the config file in:
C:\Users\gubert\Repos\Gimmonix\HotelMappingAI\aml_config\config.json
get_workspace error using subscription_id=xxxxxxxxxxxxxxxxxxxxxxx,
resource_group_name=xxxxxxxxxxxx, workspace_name=gmx-ml-mapping
Traceback (most recent call last): File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_project_commands.py",
line 320, in get_workspace workspace_name) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_base_sdk_common\workspace\operations\workspaces_operations.py",
line 78, in get raise
models.ErrorResponseWrapperException(self._deserialize, response)
azureml._base_sdk_common.workspace.models.error_response_wrapper.ErrorResponseWrapperException:
Operation returned an invalid status code 'Forbidden'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py",
line 38, in main(sys.argv) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_main_.py",
line 265, in main wait=args.wait) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_main_.py",
line 256, in handle_args run_main(addr, name, kind, *extra, **kwargs)
File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_local.py",
line 52, in run_main runner(addr, name, kind == 'module', *extra,
**kwargs) File "c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd\runner.py",
line 32, in run set_trace=False) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd\pydevd.py",
line 1283, in run return self._exec(is_module, entry_point_fn,
module_name, file, globals, locals) File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd\pydevd.py",
line 1290, in _exec pydev_imports.execfile(file, globals, locals) #
execute the script File
"c:\Users\gubert.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd\ptvsd_vendored\pydevd_pydev_imps_pydev_execfile.py",
line 25, in execfile exec(compile(contents+"\n", file, 'exec'), glob,
loc) File "c:\Users\gubert\Repos\Gimmonix\HotelMappingAI\test.py",
line 8, in ws = Workspace.from_config() File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml\core\workspace.py",
line 153, in from_config auth=auth) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml\core\workspace.py",
line 86, in init auto_rest_workspace = _commands.get_workspace(auth,
subscription_id, resource_group, workspace_name) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_project_commands.py",
line 326, in get_workspace resource_error_handling(response_exception,
WORKSPACE) File
"C:\Users\gubert.azureml\envs\myenv\lib\site-packages\azureml_base_sdk_common\common.py",
line 270, in resource_error_handling raise
ProjectSystemException(response_message)
azureml.exceptions._azureml_exception.ProjectSystemException: {
"error_details": { "error": { "code": "AuthorizationFailed",
"message": "The client 'xxxxxxxxxx#microsoft.com' with object id
'xxxxxxxxxxxxx' does not have authorization to perform action
'Microsoft.MachineLearningServices/workspaces/read' over scope
'/subscriptions/xxxxxxxxxxxxxx/resourceGroups/CarsolizeCloud - Test
Global/providers/Microsoft.MachineLearningServices/workspaces/gmx-ml-mapping'."
} }, "status_code": 403, "url":
"https://management.azure.com/subscriptions/xxxxxxxxxxxxx/resourceGroups/CarsolizeCloud%20-%20Test%20Global/providers/Microsoft.MachineLearningServices/workspaces/gmx-ml-mapping?api-version=2018-03-01-preview"
}
Try using the newest SDK version 1.0.10, this is a fairly old preview version you're using. If you still have a problem, let me know as I work on this SDK.

PyTorch Tutorial Error Training a Classifier

I just started the PyTorch-Tutorial Deep Learning with PyTorch: A 60 Minute Blitz and I should add, that I haven't programmed any python (but other languages like Java) before.
Right now, my Code looks like
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
print("\n-------------------Backpropagation-------------------\n")
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
dataiter = iter(trainloader)
images, labels = dataiter.next()
def imshow(img):
img = img / 2 + 0.5
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
imshow(torchvision.utils.make_grid(images))
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
which should be consistent with the tutorial.
If I execute this, I'll get the following error:
"C:\Program Files\Anaconda3\python.exe" C:/MA/pytorch/deepLearningWithPytorchTutorial/trainingClassifier.py
-------------------Backpropagation-------------------
Files already downloaded and verified
Files already downloaded and verified
-------------------Backpropagation-------------------
Files already downloaded and verified
Files already downloaded and verified
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 114, in _main
prepare(preparation_data)
File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 225, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
run_name="__mp_main__")
File "C:\Program Files\Anaconda3\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "C:\Program Files\Anaconda3\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Program Files\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\MA\pytorch\deepLearningWithPytorchTutorial\trainingClassifier.py", line 23, in <module>
dataiter = iter(trainloader)
File "C:\Program Files\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 451, in __iter__
return _DataLoaderIter(self)
File "C:\Program Files\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 239, in __init__
w.start()
File "C:\Program Files\Anaconda3\lib\multiprocessing\process.py", line 105, in start
self._popen = self._Popen(self)
File "C:\Program Files\Anaconda3\lib\multiprocessing\context.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Program Files\Anaconda3\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
File "C:\Program Files\Anaconda3\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__
prep_data = spawn.get_preparation_data(process_obj._name)
File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
_check_not_importing_main()
File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
is not going to be frozen to produce an executable.''')
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
Traceback (most recent call last):
File "C:/MA/pytorch/deepLearningWithPytorchTutorial/trainingClassifier.py", line 23, in <module>
dataiter = iter(trainloader)
File "C:\Program Files\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 451, in __iter__
return _DataLoaderIter(self)
File "C:\Program Files\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 239, in __init__
w.start()
File "C:\Program Files\Anaconda3\lib\multiprocessing\process.py", line 105, in start
self._popen = self._Popen(self)
File "C:\Program Files\Anaconda3\lib\multiprocessing\context.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Program Files\Anaconda3\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
File "C:\Program Files\Anaconda3\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
reduction.dump(process_obj, to_child)
File "C:\Program Files\Anaconda3\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe
Process finished with exit code 1
I already downloaded the *.py and *.ipynb.
Running the *.ipynb with jupyter works fine (but I don't want to programm in the juniper web-interface, I prefer pyCharm) while the *.py in the console (Anaconda prompt and cmd) fails with the same error.
Does anyone know how to fix this?
(I'm using Python 3.6.5 (from Anaconda) and pyCharm, OS: Win10 64-bit)
Thanks!
Bene
Update:
If it is relevant, I just set num_workers=2 to num_workers=0 (both) and then it'll work.. .
Check out the documentation for multiprocessing: programming guidelines for windows. You should wrap all operations in functions and then call them inside an if __name__ == '__main__' clause:
# required imports
def load_datasets(...):
# Code to load the datasets with multiple workers
def train(...):
# Code to train the model
if __name__ == '__main__':
load_datasets()
train()
In short, the the idea here is to wrap the example code inside an if __name__ == '__main__' statement.
Because of different implementation of multiprocessing in Windows, you need to wrap your main code with this block:
if __name__ == '__main__':
For more info, you can check the official PyTorch Windows notes.

Resources