I have this simple program:
from PIL import Image
import pyscreenshot as ImageGrab
print "hi"
im=ImageGrab.grab()
im.show()
This works perfectly fine on Ubuntu, but it gives the following error on Windows:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python27\lib\multiprocessing\forking.py", line 380, in main
prepare(preparation_data)
File "C:\Python27\lib\multiprocessing\forking.py", line 509, in prepare
'__parents_main__', file, path_name, etc
File "C:\Users\Administrator\Downloads\sample.py", line 5, in <module>
im=ImageGrab.grab()
File "C:\Python27\lib\site-packages\pyscreenshot\__init__.py", line 46, in gra
b
return _grab(to_file=False, childprocess=childprocess, backend=backend, bbox
=bbox)
File "C:\Python27\lib\site-packages\pyscreenshot\__init__.py", line 29, in _gr
ab
return run_in_childprocess(_grab_simple, imcodec.codec, to_file, backend, bb
ox, filename)
File "C:\Python27\lib\site-packages\pyscreenshot\procutil.py", line 28, in run
_in_childprocess
p.start()
File "C:\Python27\lib\multiprocessing\process.py", line 130, in start
self._popen = Popen(self)
File "C:\Python27\lib\multiprocessing\forking.py", line 258, in __init__
cmd = get_command_line() + [rhandle]
File "C:\Python27\lib\multiprocessing\forking.py", line 358, in get_command_li
ne
is not going to be frozen to produce a Windows executable.''')
RuntimeError:
Attempt to start a new process before the current process
has finished its bootstrapping phase.
This probably means that you are on Windows 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 a Windows executable.
There is no multiprocessing. I saw some other answers, but they did not help.
Can some please suggest a possible problem here?
There's a known problem with the multiprocessing module on Windows (to elaborate on roganosh remark): using multiprocessing module must be done in a function or in the __main__ section (after all the imports are initialized), not in the root of the script because of the way Windows spawns the python executable (hence the "bootstrap phase" error). No issue on Linux. Looks very much like the same issue as RuntimeError on windows trying python multiprocessing.
Try changing into this code:
from PIL import Image
import pyscreenshot as ImageGrab
if __name__ == "__main__":
im=ImageGrab.grab()
im.show()
The traceback indicates that there is multiprocessing being used in the background, not explicitly in your own code. Specifically, it is being called by pyscreenshot\procutil.py. The relevant lines of the traceback:
File "C:\Python27\lib\site-packages\pyscreenshot\procutil.py", line 28, in run
_in_childprocess
p.start()
File "C:\Python27\lib\multiprocessing\process.py", line 130, in start
self._popen = Popen(self)
Since the issue is in the library, there would be nothing you could do except modify the library yourself. However, this page says that pyscreenshot is a "Replacement for the ImageGrab Module, which works on Windows only". So instead, you should install ImageGrab library, which seems to do exactly the same thing, but is only compatible with Windows and MacOS (see here)
Related
The error occurs when I try to import the oct2py package. Here's my code:
import oct2py
Here's the error that I get:
Traceback (most recent call last):
File "c:\Users\samke\___\___\___\test.py", line 1, in <module> # I blanked out the path for privacy
import oct2py
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\oct2py\__init__.py", line 38, in <module>
octave = Oct2Py()
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\oct2py\core.py", line 83, in __init__
self.restart()
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\oct2py\core.py", line 533, in restart
self._engine = OctaveEngine(stdin_handler=self._handle_stdin,
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\octave_kernel\kernel.py", line 176, in __init__
self.repl = self._create_repl()
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\octave_kernel\kernel.py", line 402, in _create_repl
repl = REPLWrapper(cmd, orig_prompt, change_prompt,
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\metakernel\replwrap.py", line 61, in __init__
self.child = pexpect.spawnu(cmd_or_spawn, echo=echo,
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\metakernel\pexpect.py", line 29, in spawn
child = PopenSpawn(command, timeout=timeout, maxread=maxread,
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\site-packages\pexpect\popen_spawn.py", line 53, in __init__
self.proc = subprocess.Popen(cmd, **kwargs)
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 969, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\samke\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1438, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
OSError: [WinError 193] %1 is not a valid Win32 application
PS C:\Users\samke\Dev\Trading_Program\ML>
If it helps, I'm running python 3.10.5.
Thanks all!
Edit: I do have octave installed, and octave is on my path, as the oct2py documentation says is necessary.
I had similar problem and I spent half a day looking for a solution. Your problem might be similar to mine, so I will explain my situation and the solution, and hopefully, it will help solving your issue as well.
Download octave-7.1.0-w64.zip and extracted it
under the path e.g., C:\octave-7.1.0-w64
Add C:\octave-7.1.0-w64\mingw64\bin to the environment variables.
(run: edit environment variables for your account and edit the path field there).
The reason is that, octave.exe is located in this path, and this what we need to run octave in the console mode.
Run the command prompt (CMD) and type octave (i.e. calling octave.exe).
At this point, I got an error message. And this what caused that error when calling octave from oct2py.
To fix this issue, go to the octave main folder C:\octave-7.1.0-w64 and run the script post-install.bat. This adds and updates octave packages.
Once the post install script is done, run octave again from the command line (step 3). If everything is done correctly, then octave console will start octave:1>. This indicates that octave is ready to be called from oct2py without any issue.
Run python and execute import oct2py. It executed successfully.
I repeated the same procedure on two different devices and it works.
I am making a program that will allow my phone to share its clipboard with my PC. I am using Pyperclip as it appears to be the easiest and most cross-platform solution. However, when I run the code below:
...
elif "incoming_clipboard:" in server_command:
print(server_command)
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
...
I get the error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 30, in do_sync
self.handle_commands(bluetooth_socket)
File "/home/chris/Documents/Programming/Synchrony/Desktop/Phone.py", line 65, in handle_commands
pyperclip.copy(server_command.replace("incoming_clipboard: ", ""))
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 659, in lazy_load_stub_copy
return copy(text)
File "/usr/lib/python3.9/site-packages/pyperclip/__init__.py", line 158, in copy_gtk
cb = gtk.Clipboard()
File "/usr/lib/python3.9/site-packages/gi/__init__.py", line 69, in __getattr__
raise AttributeError(_static_binding_error)
AttributeError: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject". See: https://bugzilla.gnome.org/show_bug.cgi?id=709183
I know its not due to the string being invalid or anything, because 1) I am explicitly converting it from bytes to a string, and 2) it prints perfectly fine. I don't know if this is relevant, but I am using Linux, so perhaps that is affecting Pyperclip?
Do you guys have any solutions?
https://github.com/dynobo/normcap/issues/100
After going to the Github page for PyperClip, I found a similar issue that someone else had that suggested switching to PyClip. After installing PyClip and implementing it in project, I can confirm that it works perfectly without any issues.
Related to Python Multiprocessing error: AttributeError: module '__main__' has no attribute '__spec__' , but arising from different circumstances.
I'm encountering an issue in Python 3.7.4 when I try to run multiprocessing code with pdb. The issue replicates with the basic multiprocessing example from https://docs.python.org/3.6/library/multiprocessing.html :
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
This runs fine (outputs [1, 4, 9]) when run directly from Python via python.exe testcase.py. However, it does not work under pdb; python.exe -m pdb testcase.py fails with an error:
Traceback (most recent call last):
File "c:\python37\lib\pdb.py", line 1697, in main
pdb._runscript(mainpyfile)
File "c:\python37\lib\pdb.py", line 1566, in _runscript
self.run(statement)
File "c:\python37\lib\bdb.py", line 585, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "c:\users\max\desktop\projects\errortest.py", line 1, in <module>
from multiprocessing import Pool
File "c:\python37\lib\multiprocessing\context.py", line 119, in Pool
context=self.get_context())
File "c:\python37\lib\multiprocessing\pool.py", line 176, in __init__
self._repopulate_pool()
File "c:\python37\lib\multiprocessing\pool.py", line 241, in _repopulate_pool
w.start()
File "c:\python37\lib\multiprocessing\process.py", line 112, in start
self._popen = self._Popen(self)
File "c:\python37\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
File "c:\python37\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__
prep_data = spawn.get_preparation_data(process_obj._name)
File "c:\python37\lib\multiprocessing\spawn.py", line 172, in get_preparation_data
main_mod_name = getattr(main_module.__spec__, "name", None)
AttributeError: module '__main__' has no attribute '__spec__'
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> c:\python37\lib\multiprocessing\spawn.py(172)get_preparation_data()
-> main_mod_name = getattr(main_module.__spec__, "name", None)
I hesitate to think that I've found a bug in a pair of modules that have been important parts of Python for over a decade. Is something incorrect here?
This is a limitation of multiprocessing in windows. This question contains a good explanation for why this is so. A quick google search shows that the puDB may be able to help with debugging multi-processing code, but I have not used it before.
The following is from the python docs:
Functionality within this package requires that the main module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here.
This means that some examples, such as the multiprocessing.pool.Pool examples will not work in the interactive interpreter.
I need to display notifications in MacOS. Simply running the script with python can display notification. But whenever I pack the script using Pyinstaller, I get the following error. Seems like Pyinstaller is having some problem with working on Mac notifications. I also tried using pync (Python binding for terminal notifier). In all cases, simply running the app python notify.py works, but freezing the script using Pyinstaller doesn't seem to work.
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Python/2.7/site-packages/PyInstaller-2.1-py2.7.egg/PyInstaller/loader/pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/Foundation/__init__.py", line 10, in <module>
from CoreFoundation import *
File "/Library/Python/2.7/site-packages/PyInstaller-2.1-py2.7.egg/PyInstaller/loader/pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "/Users/jacob/mac-notify/build/notify/out00-PYZ.pyz/CoreFoundation", line 19, in <module>
File "/Users/jacob/mac-notify/build/notify/out00-PYZ.pyz/objc._bridgesupport", line 121, in initFrameworkWrapper
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 939, in resource_exists
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 1392, in has_resource
File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 1447, in _has
NotImplementedError: Can't perform this operation for unregistered loader type
logout
I am using the following Python script to display notification
import Foundation
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notification = NSUserNotification.alloc().init()
notification.setTitle_("TestTitle")
notification.setInformativeText_("This is sample text")
center = NSUserNotificationCenter.defaultUserNotificationCenter()
center.deliverNotification_(notification)
I had similar problems and this is how I made it work. You need not use Foundation as its making the problem with Pyinstaller (Not sure why this is causing an issue) and is not used elsewhere in your code.
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notification = NSUserNotification.alloc().init()
notification.setTitle_("TestTitle")
notification.setInformativeText_("This is sample text")
center = NSUserNotificationCenter.defaultUserNotificationCenter()
center.deliverNotification_(notification)
At this point, it may throw some error or the notification just don't show up. Just add CFBundleIdentifier key into the info.plist file generated by pyinstaller.
I am trying to learn how to use threads with python. this is the code I have been studying:
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
for i in range(10):
t = Thread(target=myfunc, args=(i,))
t.start()
the program runs fine in command prompt but when I try to run it in idle I get errors like this:
Traceback (most recent call last):
File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__
return self.func(*args)
File "C:\Python24\lib\idlelib\ScriptBinding.py", line 165, in run_module_event
interp.runcode(code)
File "C:\Python24\lib\idlelib\PyShell.py", line 726, in runcode
self.tkconsole.endexecuting()
File "C:\Python24\lib\idlelib\PyShell.py", line 901, in endexecuting
self.showprompt()
File "C:\Python24\lib\idlelib\PyShell.py", line 1163, in showprompt
self.resetoutput()
File "C:\Python24\lib\idlelib\PyShell.py", line 1178, in resetoutput
self.text.insert("end-1c", "\n")
File "C:\Python24\lib\idlelib\Percolator.py", line 25, in insert
self.top.insert(index, chars, tags)
File "C:\Python24\lib\idlelib\PyShell.py", line 315, in insert
UndoDelegator.insert(self, index, chars, tags)
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 81, in insert
self.addcmd(InsertCommand(index, chars, tags))
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 116, in addcmd
cmd.do(self.delegate)
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 216, in do
if text.compare(self.index1, ">", "end-1c"):
File "C:\Python24\lib\lib-tk\Tkinter.py", line 2784, in compare
return self.tk.getboolean(self.tk.call(
TclError: expected boolean value but got ""
Is python threading just not stable or am I doing something grossly wrong? The example came from : http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/
It sounds like a bug in IDLE, not a problem with Python. The error is coming from Tkinter, which is a Python GUI toolkit, and which IDLE probably uses. I would report it to whoever maintains IDLE.
Not everything runs properly under IDLE. This is because IDLE is a Python program in itself and has its own attributes and state that can sometimes get messed up by your own code. You can tell this is a problem with IDLE because you can see idlelib in the call stack. Also, you're not using TCL/TK at all in your application, but IDLE is, and the call stack shows that too.
I would advise switching to a more 'inert' text editor for working with Python code!