I am hoping someone can help me.
Basically, I have an arbitrary script, in this script, there are many functions and after each function is executed, print() is executed as well to give me an update. I'm using the Pysimplegui library for GUI, and was wondering if someone can help or explain what I can do to show the print output in the GUI
There are a few ways to do this that are in the documentation, here is one way.
import PySimpleGUI as sg
# This is the normal print that comes with simple GUI
sg.Print('Re-routing the stdout', do_not_reroute_stdout=False)
# this is clobbering the print command, and replacing it with sg's Print()
print = sg.Print
# this will now output to the sg display.
print('This is a normal print that has been re-routed.')
Here is the example output
Whenever you are going to use any library, first read the docs.
I am sure you can find your answer.
https://pysimplegui.readthedocs.io/en/latest/
Related
I'm trying to learn how to build a web browser bot as half learning half project for someone else and I've hit a snag.
The site I'm using as guide has:
def main():
pass
Which he claims keeps the shell window open do he can run various functions like get x,y cords of the mouse position and take screen shots.
However when I run my code exactly as he has it in the guide it immediately opens and closes.
What I don't want is something like, "make it so pressing enter closes shell instead", what needs to happen is the window stays open so I can enter various functions.
What am I doing wrong? Am I suppose to just import the code in a different shell and run the functions outside it?
The code:
import os
import time
import ImageGrab
x_pad = 0
y_pad = 61
def screenGrab():
box = (x_pad,y_pad,x_pad+1919,y_pad+970)
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) + '.png','PNG')
def main():
pass
if __name__ == '__main__':
main()
The guide is: http://code.tutsplus.com/tutorials/how-to-build-a-python-bot-that-can-play-web-games--active-11117
You have three ways:
Start the intepreter with the -i option, as suggested by Ulrich in the comments:
python -i my-script.py
This way, the interpreter will be left open as soon as your script finishes execution and a prompt will be shown.
Use pdb. This is often used for debugging, and has a different interface than the usual Python prompt. If you're not familiar with it, it might not be the best option in your case. Replace pass with these two lines:
import pdb
pdb.set_trace()
Use code. This will give you an interface much more similar to the usual Python shell and can be an alternative to pdb if you're not familiar with it:
import code
code.interact()
By the way, you were not doing anything wrong per se. The pass statement is not meant to "halt Python and start a prompt", it's just needed as a filler for functions or loops with an empty body.
I'm just finding out now that when importing a module, it seems to run through ALL the code, instead of just the one function that I want it to go through. I've been trying to find a way around this, but can't seem to get it. Here is what is happening.
#mainfile.py
from elsewhere import something_else
number = 0
def main():
print('What do you want to do? 1 - something else')
donow = input()
if donow == '1':
something_else()
while 1:
main()
#elsewhere.py
print('I dont know why this prints')
def something_else():
from mainfile import number
print('the variable number is',number)
Now, although this code KIND OF works the way I want it to, the first time when I initiate it, it will go to the main menu twice. For example: I start the program, press one, then it asks me what I want to do again. If I press one again, then it will print "the variable number is 0".
Once I get this working, I would like to be importing a lot of variables back and forth. The only issue is,if I add more import statements to "elsewhere.py" I think it will just initiate the program more and more. If I put "from mainfile import number" on line 1 of "elsewhere.py", I think this raises an error. Are there any workarounds to this? Can I make a different file? What if I made a class to store variables, if that is possible? I'm very new to programming, I would appreciate it if answers are easy to read for beginners. Thank you for the help.
As Jan notes, that's what import does. When you run import, it runs all of the code in the module. You might think: no it doesn't! What about the code inside something_else? That doesn't get run! Right, when the def statement is executed it creates a new function, but it doesn't run it. Basically, it saves the code for later.
The solution is that pretty much all interesting code should be in a function. There are a few cases which make sense to put at the top-level, but if in doubt, put it inside a function. In your particular case, you shouldn't be printing at the top level, if you need to print for some reason, put that into a function and call it when you need it. If you care when something happens, put it in a function.
On a second node, don't import your primary script in other scripts. I.e. if your mainfile.py directly, don't import that in other files. You can but it produces confusing results, and its really best to pretend that it doesn't work.
Don't try to import variables back and forth. Down that path lies only misery. You should only be importing things that don't change. Functions, classes, etc. In any other case, you'll have hard time making it do what you want.
If you want to move variables between places, you have other options:
Pass function arguments
Return values from a function
Use classes
I'll leave it is an exercise to the reader to learn how to do those things.
import executes imported code
import simply takes the Python source file and executes it. This is why it prints, because that instruction is in the code and with import all the instructions get exectued.
To prevent execution of part of imported package/module, you shall use the famous:
if __name__ == "__main__":
print("I do not print with `import`")
Note, that this behaviour is not new in Python 3, it works the same way in Python 2.x too.
Is there any way that I can create a program where it gives input to another file and and collects its output?
The best that google give me is this. And I tried to recreate (read: copying the code in some unknown manner (read: stabbing in the dark))
And I got this
import time
string="file.py"
process=subprocess.Popen(string,stdin=subprocess.PIPE,stdout=subprocess.PIPE);
process.stdin.write("3 5")
time.sleep(1)
print process.stdout.read()
And it gives me error
File "D:\Pekerjaan non website\IO\reader.py", line 3, in <module>
process=subprocess.Popen(string,stdin=subprocess.PIPE,stdout=subprocess.PIPE);
NameError: name 'subprocess' is not defined
Can anybody tell me how to create that program. (
Note: I have no knowledge in this kind of program I/O or subprocess
Note: It's up to you. Where you will explain this from my code or throw my code away and explain this from zero.
Thank you beforehand.
(PS: If my previous statement is confusing. My point is simple: Can you teach me? :))
subprocess is a stdlib module that you need to import (the same way time is) - so you just need to:
import subprocess
some time before you try to use the functions in it (usually, you want to do this near the top of your code, right underneath your current import time).
In addition to lvc's answer you should consider using Popen.communicate(). something like,
import subprocess
string="file.py"
process=subprocess.Popen(string,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
res=process.communicate("3 5")
print res[0]
In this way you don't have to use that sleep command.it'll Wait for process to terminate and return a tuple as (stdoutdata, stderrdata).
I would like to update a number without changing its placement in the output of a program. How would i go about doing this using only what is included in the standard library for python 2.7.2 ?
For example i want output like:
working on: 9
and change to:
working on: 10
without changing the line that it is displayed on. How would i go about doing this? I would also prefer that you not use cls as to prevent "flashing".
How to do this depends on your terminal type (and possibly on your platform). An easy way that works on many platforms and terminals is to use a \r character to move the cursor back to the beginning of the line:
import time
import sys
for i in range(10):
print "\rworking on:", i,
sys.stdout.flush()
time.sleep(1)
To make the line actually appear, you might need the call to sys.stdout.flush().
There isn't any easy way to do this without resorting to a GUI of some type. The standard way to create a GUI using the terminal is python's curses module. For an explanation of how to use curses in your application see: Curses Programming with Python.
I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.
Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!
You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory.
Right, I'm ashamed to admit it's actually in the documentation for InteractiveConsole after all. You can make it run in the local context by passing in the result of the locals() function to the InteractiveConsole constructor. I couldn't find a way to close the InteractiveConsole without killing the application, so I've extended it to just close the console when it catches the SystemExit exception. I don't like it, but I haven't yet found a better way.
Here's some (fairly trivial) sample code that demonstrates the debug console.
import code
class EmbeddedConsole(code.InteractiveConsole):
def start(self):
try:
self.interact("Debug console starting...")
except:
print("Debug console closing...")
def print_names():
print(adam)
print(bob)
adam = "I am Adam"
bob = "I am Bob"
print_names()
console = EmbeddedConsole(locals())
console.start()
print_names()
http://docs.python.org/3.0/library/functions.html#input
http://docs.python.org/3.0/library/functions.html#eval
def start_interpreter():
while(True):
code = input("Python Console >")
eval(code)
I'm sure, however, that their implementation is much more foolsafe than this.
Python has a debugger framework in the bdb module. I'm not sure if the IDE's you list use it but it's certainly possible to implement a full Python debugger with it.
If you want to experiment with your own Python console then this is a nice start:
cmd = None
while cmd != 'exit':
cmd = raw_input('>>> ')
try:
exec(cmd)
except:
print 'exception'
But for real work use the InteractiveConsole instead.