running python code returning false method value - python

#checkapi.py
import time
def add(a,b):
return a + b
def loop():
while True:
time.sleep(10)
print("loop running")
loop()
#apicheck.py
import checkapi
print(checkapi.add(5, 6))
output
------
apicheck.py showing "loop running"
please check out this. Why this happening.
Q. How to call a running method and get it's return value ?.

Modify checkapi.py in following way:
#checkapi.py
import time
def add(a,b):
return a + b
def loop():
while True:
time.sleep(10)
print("loop running")
if __name__ == '__main__':
loop()
this will solve your issue. if __name__ == '__main__' says Python to run loop() function only if you execute script itself like python checkapi.py, but if you import it from other module through import checkapi then loop() is not executed and you can use this module without trouble.

Related

How to stop the execution of an imported python script without exiting the python altogether?

In the example below, when I run y_file.py, I need 5 printed and Hello not printed.
How to stop the execution of an imported python script x_file.py without exiting the python altogether? sys.exit() seems to exit python altogether.
x_file.py
import sys
x = 5
if __name__ != '__main__':
pass
# stop executing x.py, but do not exit python
# sys.exit() # this line exits python
print("Hello")
y_file.py
import x_file
print(x_file.x)
As jvx8ss suggested, you can fix this by putting the print inside a if __name__ == "__main__": conditional. Note the equality "==" instead of inequality "!=".
Final code:
import sys
x = 5
if __name__ == "__main__":
# stop executing x.py, but do not exit python
# sys.exit() # this line exits python
print("Hello")
You should place your code you don't want to run in the import inside an if __name__ == "__main__" however, there is an extremely bad way to do what you want that I can think of using Exception
# x_file.py
x = 5
if __name__ != '__main__':
raise Exception(x)
print("Hello")
# y_file.py
try:
import x_file
except Exception as e:
print(e.args[0])

How to interrupt a thread in python 2?

I've encountered an uninterruptable code in Python 2.7.
from time import sleep
import threading
def fun():
for i in range(100):
print(i)
sleep(0.1)
if __name__ == '__main__':
threading.Timer(1, fun).start()
First, how come it is uninterruptable? (It ignores SIGINT)
In Python 3 this code interrupts fine.
Second, what changes should I make for it to respond to SIGINT before it finishes the loop?
In my actual case, it's an infinite loop :.(
I'm not yet sure why does it happen, but this phenomenon is mentioned in Python 3.2 bug fix report.
I found a workaround by unfolding the following code:
def fun():
while True:
... my code ...
sleep(0.1)
if __name__ == '__main__':
threading.Timer(1, fun).start()
Into:
def fun():
... my code ...
threading.Timer(0.1, fun).start()
if __name__ == '__main__':
threading.Timer(1, fun).start()

How could a function look like, that can add an other function to a list of functions that run parallel in python?

def update():
while True:
loadData()
def main():
doStuff()
addToParallelFunctions(update)
doOtherStuff()
if __name__ == '__main__':
addToParallelFunctions(main)
How could that addToParallelFunctions function look like, so that update runs parallel to main and that I can add other functions to run also parallel to the main?
I've tried that, but it paused the main function and ran the other function until she was finished.
from multiprocessing import Process
def addProcess(*funcs):
for func in funcs:
Process(target=func).start()
I enhanced your example:
It works for me. Main script and function continue both.
import time
from multiprocessing import Process
def addProcess(*funcs):
for func in funcs:
Process(target=func).start()
def update():
for i in range(20):
print(i)
time.sleep(2)
def main():
print("start")
addProcess(update)
print("Main function continues")
if __name__ == '__main__':
addProcess(main)
print("main script continues")
Next time, please post an example that is reproducible.

Using sys.exit() within a function

I would like to use sys.exit() within a function my_func(), how do I use it?
def my_func():
try:
some_method()
except:
print('Error')
sys.exit()
if __name__ == "__main__":
my_func()
You need to import sys before you can use it. Just add it to the top of your script:
import sys
def my_func():
try:
some_method()
except:
print('Error')
sys.exit()
if __name__ == "__main__":
my_func()
I see three programming issues. Besides the missing import sys, you flag an error but simply call sys.exit() which exits with a zero indicating success to the invoker -- it needs to exit non-zero to indicate error. Finally you print the error message to sys.stdout when it really should go to sys.stderr. A rework of your code:
import sys
def my_func():
try:
some_method()
except:
print('Error', file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
my_func()
Fortunately, Python allows us to combine these last two issues by instead doing:
import sys
def my_func():
try:
some_method()
except:
sys.exit('Error')
if __name__ == "__main__":
my_func()
This will exit non-zero and print the message to sys.stderr.

Python: how to terminate a function of a script from another script

I have a script main.py which called a function fun from a library.
I want to exit only from fun continuing the script main.py, using for this purpose another script kill_fun.py.
I tried to use different bash commands (using os.system) with ps, but the pid it gives me is referred only to main.py.
Example:
-main.py
from lib import fun
if __name__ == '__main__':
try:
fun()
except:
do_something
do_something_else
-lib.py
def fun():
do_something_of_long_time
-kill_fun.py
if __name__ == '__main__':
kill_only_fun
You can do so by run fun in a different process.
from time import sleep
from multiprocessing import Process
from lib import fun
def my_fun():
tmp = 0
for i in range(1000000):
sleep(1)
tmp += 1
print('fun')
return tmp
def should_i_kill_fun():
try:
with open('./kill.txt','r') as f:
read = f.readline().strip()
#print(read)
return read == 'Y'
except Exception as e:
return False
if __name__ == '__main__':
try:
p = Process(target=my_fun, args=())
p.start()
while p.is_alive():
sleep(1)
if should_i_kill_fun():
p.terminate()
except Exception as e:
print("do sth",e)
print("do sth other thing")
to kill fun, simply echo 'Y' > kill.txt
or you can write a python script to write the file as well.
Explain
The idea is to start fun in a different process. p is a process handler that you can control. And then, we put a loop to check file kill.txt to see if kill command 'Y' is in there. If yes, then it call p.terminate(). The process will then get killed and continue to do next things.
Hope this helps.

Categories

Resources