I am trying to write some python code using tornado. Here is my code.
import sys
import tornado.ioloop
import tornado.web
import constants
class student():
name = ""
class MainHandler(tornado.web.RequestHandler):
def get(self):
loader = tornado.template.Loader(".")
print "MainiiiHandler"
self.write(loader.load("base.html").generate(pics=constants.pics))
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
So when i visit 127.0.0.1:8888, it should print MainiiiHandler in terminal. When i run python code with 'python test.py', it turns out actually like this. But when i run with :make in vim, it won't print MainiiiHandler. Because i really like the make function in vim, so can you help me solve this problem.
Check how
makeprg is python %
is written.
:set makeprg="python %"
does NOT work for me (echoes an empty string)
while
:set makeprg=python\ %
actually DOES work.
(if it doesn't help) This is what :h make shows:
The program given with the 'makeprg' option is started (default "make") with the optional [arguments] and the output is saved in the errorfile (for Unix it is also echoed on the screen).
If your system is not Unix, I suppose you have to supply the code that will print the contents of errorfile for you (don't know for sure as I tested it only under Linux).
Related
i have a python script that i want to close console and then execute again the script from the beginning. Can you help me with this?
I need to close it when i execute a function on the script. Then reopen the file so it's ready again for doing something.
You should import your script instead. You can import python files from same directory. An example:
rerun.py:
def print_stuff():
print('stuff')
runner.py:
from rerun import print_stuff
print_stuff()
Use flask. It is made for this. Go take a look at http://flask.pocoo.org/docs/1.0/quickstart/.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def some_function():
print('do stuff here')
I want to import a python script in to another script.
$ cat py1.py
test=("hi", "hello")
print test[0]
$ cat py2.py
from py1 import test
print test
If I execute py2.py:
$ python py2.py
hi
('hi', 'hello')
Can I anyway mute the first print which is coming from the from py1 import test?
I can't comment the print in py1, since it is being used somewhere else.
py1.py use an if __name__=="__main__":
So like your py1.py would look like:
def main():
test=("hi", "hello")
print test[0]
if __name__=="__main__":
main()
This will allow you to still use py1.py normally, but when you import it, it won't run the main() function unless you call it.
This explains what's going on
Simply open the /dev/null device and overwrite the sys.stdout variable to that value when you need it to be quiet.
import os
import sys
old_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
from py1 import test
sys.stdout = old_stdout
print test
You might want to consider changing the other script to still print when its run 'in the other place' - if you're running py1 as a shell command, try to make sure all "executable statements" in a file are inside a block.
if __name__ == "__main__":
print test
(see What does if __name__ == "__main__": do?)
This would fix the underlying issue without having you do weird things (which would be redirecting the standard out, and then putting it back etc), or opening the file and executing line by line on an if block.
You could implement this functionality with methods:
py1.py
test=("hi", "hello")
def print_test():
print(test)
def print_first_index():
print(test[0])
py2.py
import py1
py1.print_test()
As MooingRawr pointed out, this would require you to change whichever classes use py1.py to import it and call the py1.print_first_index() function which may not be to your liking.
I am a newbie in process of learning python and currently working on a automation project.
And i have N numbers of testcase which needs to be run on reading material people suggest me to use nosetest.
What is the way to run multiple testcase using nosetest?
And is the correct approach doing it:
import threading
import time
import logging
import GLOBAL
import os
from EPP import EPP
import Queue
import unittest
global EPP_Queue
from test1 import test1
from test2 import test2
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class all_test(threading.Thread,unittest.TestCase):
def cleanup():
if os.path.exists("/dev/epp_dev"):
os.unlink("/dev/epp_dev")
print "starts here"
server_ip ='192.168.10.15'
EppQueue = Queue.Queue(1)
EPP = threading.Thread(name='EPP', target=EPP,
args=('192.168.10.125',54321,'/dev/ttyS17',
EppQueue,))
EPP.setDaemon(True)
EPP.start()
time.sleep(5)
suite1 = unittest.TestLoader().loadTestsFromTestCase(test1)
suite2 = unittest.TestLoader().loadTestsFromTestCase(test2)
return unittest.TestSuite([suite1, suite2])
print "final"
raw_input("keyy")
def main():
unittest.main()
if __name__ == '__main__':
main()
Read
http://ivory.idyll.org/articles/nose-intro.html.
Download the package
http://darcs.idyll.org/~t/projects/nose-demo.tar.gz
Follow the instructions provided in the first link.
nosetest, when run from command line like 'nosetest' or 'nosetest-2.6' will recursively hunt for tests in the directory you execute it in.
So if you have a directory holding N tests, just execute it in that directory. They will all be executed.
I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...
#connect.py
import user, db
import paramiko, time, os
paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
def __init__(self):
#Call DB Functions
database = db.Database()
#Set Transport
self.transport = paramiko.Transport((user.hostname, user.port))
#User Credentials
username = user.username
password = user.password
self.transport.connect(username = username, password = password)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
print "Set your credentials in user.py for now!"
msg = "Connecting as: %s, on port number %d" % (user.username, user.port)
print msg
def disconnect(self):
print "Closing connection..."
self.sftp.close()
self.transport.close()
print "Connection closed."
Pretty straightforward. Connect and disconnect.
This connect.py file is being imported into a main.py (which is my gui)
#main.py
import connect
from PySide import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
windowWidth = 550
windowHeight = 350
self.establishedConnection = ""
connectButton = self.createButton("&Connect", self.conn)
disconnectButton = self.createButton("&Disconnect", self.disconnect)
grid = QtGui.QGridLayout()
grid.addWidget(connectButton, 3, 3)
grid.addWidget(disconnectButton, 4, 3)
grid.addWidget(self.createList(), 1, 0, 1, 4)
self.setLayout(grid)
self.resize(windowWidth, windowHeight)
self.setWindowTitle("FTP Program")
def conn(self):
connection = connect.Connection()
self.establishedConnection = connection
def disconnect(self):
self.establishedConnection.disconnect()
def createButton(self, text, member):
button = QtGui.QPushButton(text)
button.clicked.connect(member)
return button
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
gui = Window()
gui.show()
sys.exit(app.exec_())
The issue is disconnecting.
I was thinking __init__ would create an instance of the Connection() class. If you look on main.py you can see that I tried to create the variable self.connectionEstablished in order to save the object so I could call disconnect on it later.
Where am I going wrong? I'm fairly new to python and other non-web languages(I spend most of my time writing RoR and php apps).
No errors are shown at any time and I started this app out as a terminal app so I do know that connect.py does work as intended.
Edit: So I guess Senderle got a connection closed message, which is what I'd like to see as well but I'm not. I'll mark a best answer if I see something that solves my problem.
Edit Solved: Pushed connect.py and main.py into one file to simplify things. And for some reason that solved things. So who knows whats going on. I'm still going to hold off on 'best answer'. If someone can tell me why I can't have a split file like that then I'm all ears.
I tried the code and it ran fine. I made only a few changes.
First, I didn't know what "user" and "db" are, so I commented out
import user, db
and
database = db.Database()
and used my own data for username, password, etc.
Second, the PySide module isn't available via my package manager, so I used PyQt4 instead. It didn't like grid.addWidget(self.createList(), 1, 0, 1, 4) so I commented that out, and everything worked as expected.
Further thoughts: When there were connection errors, there was some console feedback consisting of stack traces, but nothing more, and self.establishedConnection remained a string, causing self.establishedConnection.disconnect() to fail. So perhaps there's a connection problem?
EDIT: Aaaahhhhh, I just saw this: "No errors are shown at any time." Are you running this from a terminal or double-clicking an executable? If you start it from a terminal, I bet you'll see stacktraces in the terminal. The gui doesn't close when the code hits an exception.
EDIT2: If joining the files fixes the problem, then I am certain the problem cannot have anything to do with python itself. This has to be a problem with eclipse. You say that connection.py began as a terminal app, so you must be able to run python apps from the command line. Try the following: put main.py, connect.py, etc. in a directory of their own, open a terminal, and run python main.py. If it works as expected, then the problem has something to do with eclipse.
You are not calling conn() in the constructor.
Is there a better way to only print when run as a script, when __name__ == '__main__' ?
I have some scripts that I also import and use parts of.
Something like the below will work but is ugly, and would have to be defined in each script separately:
def printif(s):
if globals()['__name__'] == '__main__':
print (s)
return
I looked briefly at some of python's logging libraries but would prefer a two lighter solution...
edit:
I ended up doing something like this:
# mylog.py
import sys
import logging
log = logging.getLogger()
#default logging level
log.setLevel(logging.WARNING)
log.addHandler(logging.StreamHandler(sys.stdout))
And from the script:
import log from mylog
...
log.info(...)
log.warning(...)
...
if __name__ == '__main__':
#override when script is run..
log.setLevel(logger.INFO)
This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.
run_as_script = False
def printif(s):
if run_as_script:
print (s)
return
if __name__ == '__main__':
run_as_script = True
In light of user318904's comment on my other answer, I'll provide an alternative (although this may not work in all cases, it might just be "good enough").
For a separate module:
import sys
def printif(s):
if sys.argv[0] != '':
print (s)
Using a logging library is really not that heavyweight:
import logging
log = logging.getLogger('myscript')
def dostuff(...):
....
log.info('message!')
...
if __name__ == '__main__':
import sys
log.setLevel(logging.INFO)
log.addHandler(logging.StreamHandler(sys.stdout))
...
One wart is the "WARNING: no handlers found for myscript" message that logging prints by default if you import this module (rather than run it as a script), and call your function without setting up logging. It'll be gone in Python 3.2. For Python 2.7, you can shut it off by adding
log.addHandler(logging.NullHandler())
at the top, and for older versions you'd have to define a NullHandler class like this:
class NullHandler(logging.Handler):
def emit(self, record):
pass
Looking back at all this, I say: go with Gerrat's suggestion. I'll leave mine here, for completeness.