Interrupt a Python function and manipulate the variables - python

I have the file main.py containing the code
def my_function():
a = 0
b = 1
c = 2
if __name__ == "__main__":
my_function()
I execute this script from a terminal / shell.
If I run the script with python -i main.py all the variables are already gone because the function my_function has ran out of scope.
How do I interrupt the running of the script after the command a = 0 and set a to the value 1?
EDIT
My goal with this question is to learn how I can apply some commands on variables that are the result of a function, even after the function has finished. So the code I wrote above is just a (minimum working) example.

You can use Python debuger's set_trace() to break into the debugger from a running program and manipulate variables.
Use debugger command c(ont(inue)) to continue execution.
def my_function():
a = 0
import pdb
pdb.set_trace()
b = 1
c = 2
if __name__ == "__main__":
my_function()

Related

Python. Open another program in for loop

I'm creating a program in Python and I have a problem with a for loop and opening program in this loop.
The program is supposed to run e.g. 5 times and it only runs once
import subprocess
z = int(input())
def run():
subprocess.run('notepad.exe')
a = 0
while(a<z):
a = a + 1
run()
I've tried creating a function and replacing the for loop with a while loop but it doesn't work. Sorry for my English
Use subprocess.Popen('notepad.exe'), this will put the process in the background.
subprocess.run() will wait for the exit code I think, which waits until you close the notepad.
So full code is
import subprocess
z = int(input())
def run():
subprocess.Popen('notepad.exe')
a = 0
while(a<z):
a = a + 1
run()
You need to do pip install AppOpener first (or however you install modules for your device).
from AppOpener import open
z = int(input('Enter the number of times to open notepad: '))
def run():
open('notepad')
a = 0
while(a < z):
a = a + 1
run()
Additionally, for running any different apps, just change 'notepad' to the name of the app. (For Example: 'facebook')
Now it depends what you want. subprocess.run() opens the program, and pauses the code until you close notepad. Then, it will re open it, and do it z many times.
If you want to open z many instances of notepad at the same time you need to use `subprocess.Popen('notepad.exe', '-new-tab')
From the look of the code this may or may not be an issue. Python doesn't know where notepad.exe is located. You need to add the full path of the executable file. For example, try this:
import subprocess
z = int(input())
def run():
subprocess.run(r'C:\WINDOWS\system32\notepad.exe') #For most people this is the location of notepad.exe
a = 0
while(a<z):
a = a + 1
run()

Check if a functon runs as an imported module [duplicate]

This question already has answers here:
python: how to tell if file executed as import vs. main script?
(3 answers)
Closed 1 year ago.
Is possible to check within a function if the given function runs within the script or runs as an imported module in another script?
For example:
def func():
if func was imported:
do this
else: # it runs within the script
do that
Rewrite your function like this:
def func():
if __name__ == '__main__':
print("I'm running within this script.")
else:
print("I was imported to another script.")
if __name__ == '__main__':
func()
If you run the current script, you'll get the following output:
./test.py
>>> I'm running within this script.
If you run from test import func; func() you'll get the following:
>>> I was imported to another script.
Every module has a __name__, if it is imported it will be equal to the name of the module, else it will be '__main__' if it is in the script you run
def func():
if __name__ == '__main__':
# Do this
else:
# Do that

Python 2.7: import Module and function and assign variable to new variable

I'm already struggeling some hours with a problem within my python project.
The situation is as follows:
I have a script A.py and a Script B.py
**Script A.py:**
#in this script the function def main() is running
def main():
#some coding in here
x=str(body)#then i assign the string of the variable body to a new variable x
#some other coding in here
if __name__=='__main__':
main()
REMIND: this a pseudo code to explain my struggle (the script as a standalone module is working properly) !
Now I have Script B.py (in the same folder)
**Script B.py** #in this script i try to run Script A.py and assign the value of variable x to a new variable in order to do furhter processing with it.
import A
A.main() # When importing the module and excuting its main() function by running B.py I see the values of variable x appearing on my screen
QUESTION: How can I assign the value of variable x now to a new variable so that i can do further processing with it in B.py ? Is this even possible ?
Cause after calling the main function of A.py no other operations are processed.
Please consider that I'm a relatively newby regaring programming over several modules.
I would be very glad for any help.
Thank you very much in advance
Kind regards
Slin
Ok i tried your approaches but still not getting the desired result.
A.py is a AMQP subscribing script (https://www.rabbitmq.com/tutorials/tutorial-one-python.html) (see below):
import pika
credentials = pika.PlainCredentials('admin', 'admin')
connection = pika.BlockingConnection(pika.ConnectionParameters('Ipaddress',
5672,
'/',
credentials))
#connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs',
queue=queue_name)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
x = str(body)
print str(x)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
if __name__ == '__main__':
main()
B.py:
import pika
import A
A.main()
With the approaches so far i get the same as shown with the coding above.
I would like to assign x (which values can chane when A is running) to a new variable within B.py to do some processing to publish it afterwards with the counterpart script of A.py.
When executing B.py i receive:
[*] Waiting for logs. To exit press CTRL+C
['20'] #this is the string of variable x from script A
Now i want to assign this ['20'] to a new variable wihtin B.py.. but the script B.py keeps running A.main() (which is logical cause it is a loop).
Thanks so far for your support.
Kind regards
You could return the value of x to script B using the return statement:
return str(body)#then i assign the string of the variable body to a new variable x
Then get this value in script B by storing it in a variable x = A.main().
Make x as a global variable inside A.py
**Script A.py:**
#in this script the function def main() is running
x = ''
def main():
global x
#some coding in here
x=str(body)
#then i assign the string of the variable body to a new variable x
if __name__=='__main__':
main()
Now you can access that x from B.py as A.x
Just treat it like you do with any other module. In script A, create a function as you have called main. In it you have to have a variable that you can insert from the other script, call it body.
Script A:
def main(body):
...
return x
Next you import the other script like you would any other model, using import _.py as _. The you use the function as you would in the other script, B. It is as if you are importing an object A and calling its method b.
Script B:
import a.py as A
object = A.main(thing2string) # or object = A.main() if the script b has something to return
Now you have the object that is created in A from that you can process in be. For example,
processed = [object[i] for i in object]
# ... processing steps
I don't know if you can have it notify you on change. But you use a timer to check if the value is updated and use an if statement to update if it has.
Summary:
You have to add the return line in script A. And you have to set a variable equal to it in script b. This new variable then becomes whatever b returns.

Solution to get output for python project

I am doing a simple project on my Pycharm IDE.
My code is this:
import webbrowser
import time
socialMediaUrls = ["www.google.com","www.edureka.com"]
techUrls = ["www.udacity.com","www.dailymotion.com"]
def open_tabs(url_list):
for element in url_list:
webbrowser.open_new_tab(element)
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
main()
but after running I am getting this message:
C:\Users\adc\AppData\Local\Programs\Python\Python36-32\python.exe
C:/Users/adc/PycharmProjects/untitled1/ur.py
Process finished with exit code 0
And I am getting same message for all my projects. What should I do?
You should call main in that way:
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
if __name__ == "__main__":
main()
Also I see that your code contains some other errors. For example, in Python there is False keyword, not false. Lines with open.tab and open_tabs will not work too.
Currently, no instructions are reachable in your script (besides the import statements)
in:
def main():
webbrowser.open("www.youtube.com",new=0,autoraise=false)
time.sleep(1)
open.tab(socialMedialUrls)
open_tabs(techUrls)
main()
indentation suggests that you're performing a recursive call (which isn't what you want).
Unindent main() to make sure you execute something in your script.
Or put the instructions of main at zero-indent level outside any procedure (in that case, it is executed even when importing the module, probably not important here)
(note that python programs don't need a main(), this isn't C)

Python main function not working [duplicate]

This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 6 years ago.
I am writing a simple Python program with some functions, one of which is a main() function executes the other functions. However when I run the code below there is no output. Can someone tell me if they see an error in the structure?
def print1():
print("this is also a function")
def print2():
print("this is a function")
def main():
print1()
print2()
You need to call main(). Right now it is just a definition. What use is an entry in a dictionary if nobody uses the word?
def print1():
print("this is also a function")
def print2():
print("this is a function")
def main():
print1()
print2()
main()
It is common in Python programs to do things differently depending on if the file is being imported or run. When a file is executed, the __name__ variable is set either to '__main__' or the name of the file. It is set to '__main__' if the file is being executed as a python script, and it is set to the name of the file if it is being imported. You can use this information so that you don't actually run anything if it is just being imported instead of being run as a python script:
if __name__ == '__main__':
main()
That way, you can import the module, and use the functions without main() being called. If it is run as a python script, however, main() will be called.
Add this to the bottom of your code.
if __name__ == "__main__":
main()
See https://docs.python.org/2/library/main.html
Main needs to be called explicitly. You can do it without the if statement, but this allows your code to be either a module or a main program. If it is imported as a module, main() won't be called. If it is the main program then it will be called.
You are thinking like a C programmer. In this case python acts more like a shell script. Anything not in a function or class definition will be executed.
You need to call main() in order for it to run.
I believe what you mean to be doing is
def print1():
print("this is also a function")
def print2():
print("this is a function")
if __name__ == '__main__':
print1()
print2()
Call this script something.py and then run python something.py from your command line.

Categories

Resources