I am using the module Inputs to get key input in Python when I run this code below
import inputs
events = inputs.get_key()
if __name__ == '__main__':
freeze_support()
I get this error:
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.
Exception ignored in: <bound method InputDevice.__del__ of inputs.Keyboard("/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd")>
Traceback (most recent call last):
File "C:\Users\26099\AppData\Local\Programs\Python\Python36\lib\site-packages\inputs.py", line 2541, in __del__
File "C:\Users\26099\AppData\Local\Programs\Python\Python36\lib\multiprocessing\process.py", line 113, in terminate
AttributeError: 'NoneType' object has no attribute 'terminate'
This only happens when i run it in a python file. If i run it in the python shell i don't get this error.
freeze_support() has to be properly imported and be the first thing run. That would look like this:
from multiprocessing import freeze_support
import inputs
freeze_support()
if __name__ == '__main__':
events = inputs.get_key()
So the answer given by Nathaniel Taulbut was what I needed but it didn't run in a loop which is what I needed so I changed the code a bit to run in a loop.
from multiprocessing import freeze_support
import inputs
freeze_support()
def Keys():
if __name__ == '__main__':
while True:
events = inputs.get_key()
for event in events:
print(event.code)
Keys()
As far as I have tested it works but is there a way I could get this code working without if __name__ == '__main__'
Related
def fun:
path = "C:\\Users\\siya\\Desktop\\data"
if filesnames.endswith('.xlsm'):
file_path = Path(os.path.join(path, filesnames))
sheet = pd.read_excel(file_path, 'sheetname', index_col=False)
print(sheet)
def func_process:
with Pool(processes=12) as pool:
filesnames = os.listdir(path)
pool.map(fun, filesnames)
func_process()
getting an error when i try use the pool in func_process instead of
if __name__ == '__main__'
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.
can any one help how execute the pool with out using main function
I'm trying to use Spleeter to get a dictionary of the separate tracks (vocals, bass, etc.) from a wav file and the following is my code:
def seperator():
separator = Separator('spleeter:4stems')
file = "test.wav"
audio_loader = AudioAdapter.default()
sample_rate = 44100
waveform, _ = audio_loader.load(file, sample_rate=sample_rate)
prediction = separator._separate_librosa(waveform, file)
print(prediction['vocals'])
def do_seperation():
__name__ = '__main__'
if __name__ == '__main__':
seperator()
However, I get the following error message
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.
This seems to be a common error in Spleeter as I've gotten this error message before but have been able to resolve this by using if __name__ == '__main__': as a wrapper for my function but this time it isn't working. Is there any way to resolve this weird error? Any help appreciated, thanks!
import time
import multiprocessing
def mydef(arg):
time.sleep(arg)
print("Seleeped for 1 Sec")
pro=[]
for _ in range(15):
p=multiprocessing.Process(target=mydef,args=[1])
p.start()
pro.append(p)
for proo in pro:
proo.join()
error
RuntimeError File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\process.py", line 608, in _adjust_process_count
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.
results = executor.map(do_something, secs)
I want to execute a Python file from another Python file and show all print() outputs and error outputs without waiting (realtime).
The simplified version of my code is as follows and I would like to show "start" and an error message without waiting for "end" (the end of the script).
def main():
# Function that takes a long time (in my actual code)
x += 1 # this raises an error
if __name__ == "main":
print("start")
main()
print("end")
I also have run.py:
import subprocess
def run():
subprocess.run(["python", "main.py"])
if __name__ == '__main__':
run()
I tried this blog post and several other similar answers on stackoverflow, but none of them worked, so I decided to put my original code here, which is above.
The following seems to work for me (on Windows). It uses subprocess.Popen() to execute the other script because this gives more control over what goes on. It turns buffering off to eliminate any delays that might cause, plus it redirects stderr to stdout to so all output can be retrieved from a single source.. Also note it also includes the correction #Ketan Mukadam mentions is his answer tregarding the value of __name__ in your first script.
main_script.py:
def main():
# Function that takes a long time (in my actual code)
x += 1 # this raises an error
if __name__ == '__main__':
print("start")
main()
print("end")
run.py:
import subprocess
import sys
def run():
kwargs = dict(bufsize=0, # No buffering.
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, # Redirect stderr to stdout.
universal_newlines=True)
args = [sys.executable, 'main_script.py']
with subprocess.Popen(args, **kwargs).stdout as output:
for line in output:
print(line, end='') # Process the output...
if __name__ == '__main__':
run()
Output from executing run.py:
start
Traceback (most recent call last):
File "main_script.py", line 10, in <module>
main()
File "main_script.py", line 6, in main
x += 1 # this raises an error
UnboundLocalError: local variable 'x' referenced before assignment
Is this line a mistake?
if __name__ == "main":
The symbol is __main__ set by interpreter and not main. It is possible that because of this typo error no code is running from main script. Try first executing the main script directly on command shell.
import Queue
from multiprocessing.managers import BaseManager
BaseManager.register('get_queue', callable=lambda: Queue.Queue())
manager = BaseManager(address=('', 5000), authkey='abc')
manager.start()
manager.shutdown()
This code will throw a exception
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.
but after I add if __name__ == '__main__': freeze_support()
It will throw anther exception, how to fix it?
My os is window7
This error message is displayed when using multiprocessing with the 'spawn' start method (default on platforms lacking fork like windows), and not protecting your code with a if __name__ = '__main__' guard.
The reason is that with the 'spawn' start method a new python process is spawned, which then in turn has to import the __main__ module before it can proceed to do it's work. If your program does not have the mentioned guard, that subprocess would try to execute the same code as the parent process again, spawning another process and so on, until your program (or computer) crashes.
The message is not ment to tell you to add the freeze_support() line, but to guard your program:
import Queue
from multiprocessing.managers import BaseManager
def main():
BaseManager.register('get_queue', callable=lambda: Queue.Queue())
manager = BaseManager(address=('', 5000), authkey='abc')
manager.start()
manager.shutdown()
if __name__ == '__main__':
# freeze_support() here if program needs to be frozen
main() # execute this only when run directly, not when imported!