I am trying to run the following HelloWorld Script at Command Line
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/", MainHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
and I am getting the following error
File "helloworld.py", line 17, in ?
import tornado.httpserver
File "/home/username/public_html/tornado-1.2.1/tornado/httpserver.py", line 28, in ?
from tornado import ioloop
File "/home/username/public_html/tornado-1.2.1/tornado/ioloop.py", line 184
action if action is not None else signal.SIG_DFL)
^
SyntaxError: invalid syntax
Brand New to Python, can someone explain what the problem being pointed out is? P.S. helloworld.py is in the /home/username/public_html/tornado-1.2.1/ directory, and there is a tornado subdirectory in the same directory.
Edit: (Ignore this edit now)
The command i am running is
python helloworld.py
The result of python -V is
Python 2.4.3
Unfortunately Tornado doesn't work with versions before 2.5 so this might be the problem. However, I have installed Python 2.6.6 How do I ensure that it is running with the correct version of Python and not the older one?
EDIT II
Now I have set Python to 2.6.6
and running
python helloworld.py
doesn't produce any output. The program just freezes at the command line.
Any thoughts here?
As you've found out yourself, the problem is that python 2.4 does not support the conditional expression operator.
How you can switch to another Python version depends on your system. On debian and Ubuntu, you can edit /usr/share/python/debian_defaults. On all Linux systems, you can remove /usr/bin/python and link to the version you'd like:
sudo mv /usr/bin/python /usr/bin/python.dist
sudo ln -s /usr/bin/python2.5 /usr/bin/python
Alternatively, you can modify the PATH environment variable to contain a directory with the desired python binary before /usr/bin (this is probably the way to go on Windows). You can make this permanent by editing ~/.profile (at every login) or ~/.bashrc (in interactive, bash shells).
To get Python 2.6 as default make sure you've mapped python to /usr/bin/python2.6 in your .bash_rc.
If you're trying to fix this, you'll need to go through and swap out the conditional operator:
if seconds is not None:
signal.signal(signal.SIGALRM,
action if action is not None else signal.SIG_DFL)
This syntax (action if action is not None else signal.SIG_DFL) is only available in Python 2.>=5
The alt? Not as nice but workable:
if seconds is not None:
if action is not None:
tmpaction = action
else
tmpaction = signal.SIG_DFL
signal.signal(signal.SIGALRM,tmpaction)
I HIGHLY RECOMMEND THAT YOU SIMPLY UPGRADE TO THE LATEST VERSION OF PYTHON. THERE IS NO GUARANTEE THAT YOU WON'T FIND OTHER ISSUES. (Unless, of course, you want the learning experience).
Related
Looking to use a include a redis server for storing application specific data with my pyinstaller bundled application.
Before getting into it hands-on, need some guidance.
Are these the steps to follow for it?
(1) Bundle redis-server executable. And run it as a standalone application via some script in my bundled package.
(2) Use redis client packages in python to connect to the redis-server
I guess (2) should surely work. But is there any easy way of doing (1).
You can bundle arbitrary binaries with the --add-binary option on the command line or the binaries argument to the Analysis call in your .spec file. Check out the manual for details, but one example:
pyinstaller -F main.py --add-binary=`which redis-server`:bin
I don't know of a way to run arbitrary executables, but you could have some python code in your app to detect when you're bundled, find the redis binary, and start it up. Again, you can check out the documentation for details on how to go about this but, again, a example of how this could look (optional contextmanager elegance stolen from another answer):
import sys
import os
import subprocess
from contextlib import contextmanager
#contextmanager
def bundledredis():
proc = subprocess.Popen(
[os.path.join(sys._MEIPASS, 'bin', 'redis-server')])
yield
proc.terminate()
#contextmanager
def optional(condition, context_manager):
if condition:
with context_manager:
yield
else:
yield
def realmain():
print('doing stuff')
def main():
with optional(getattr(sys, 'frozen', False), bundledredis()):
realmain()
if __name__ == '__main__':
main()
I have a Django project, and I want to use Celery. I've installed Celery for python3, and then I run this command : sudo celery -A myApp worker -l info
But in the log, I see that it's Celery of python2.7 which is used : File "/Library/Python/2.7/site-packages
Any idea how for me to use the Celery installed for python3 ?
Ok, thanks to #Wayne I've found the solution.
First, use this command to see where the head of celery is : head -n 10 /usr/local/bin/celery
For myself, this is what I get :
#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'celery==3.1.23','console_scripts','celery'
__requires__ = 'celery==3.1.23'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('celery==3.1.23', 'console_scripts', 'celery')()
)
I see that the first shebang (#!/usr/bin/python) use the wrong python version.
Then, I've changed the first shebang : #!/usr/bin/env python3 and save the file. Now celery point to python3.
I use PyCharm/IntelliJ community editions from a wile to write and debug Python scripts, but now I'm trying to debug a Python module, and PyCharm does a wrong command line instruction parsing, causing an execution error, or maybe I'm making a bad configuration.
This is my run/debug configuration:
And this is executed when I run the module (no problems here):
/usr/bin/python3.4 -m histraw
But when I debug, this is the output in the IntelliJ console:
/usr/bin/python3.4 -m /opt/apps/pycharm/helpers/pydev/pydevd.py --multiproc --client 127.0.0.1 --port 57851 --file histraw
/usr/bin/python3.4: Error while finding spec for '/opt/apps/pycharm/helpers/pydev/pydevd.py' (<class 'ImportError'>: No module named '/opt/apps/pycharm/helpers/pydev/pydevd')
Process finished with exit code 1
As you can see, the parameters are wrong parsed, and after -m option a IntelliJ debug script is passed before the module name.
I also tried just put -m histraw in the Script field, but doesn't work, that field is only to put Python script paths, not modules.
Any ideas?
There is another way to make it work.You can write a python script to run your module.Then just configure PyCharm to run this script.
import sys
import os
import runpy
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '..')
sys.path.insert(0, path)
runpy.run_module('<your module name>', run_name="__main__",alter_sys=True)
Then the debugger works.
In PyCharm 2019.1 (professional), I'm able to select run as module option under configurations, as below
I found it easiest to create a bootstrap file (debuglaunch.py) with the following contents.
from {package} import {file with __main__}
if __name__ == '__main__':
{file with __main__}.main()
For example, to launch locustio in the pycharm debugger, I created debuglaunch.py like this:
from locust import main
if __name__ == '__main__':
main.main()
And configured pycharm as follows.
NOTE: I found I was not able to break into the debugger unless I added a breakpoint on main.main() . That may be specific to locustio, however.
The problem is already fixed since PyCharm 4.5.2. See corresponding issue in PyCharm tracker:
https://youtrack.jetbrains.com/issue/PY-15230
I tried this minimal example:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(debug = True)
When I try python hello.py, everything goes well. However, when I try to run it from Textmate (Shift + Cmd + R) an error is thrown:
Traceback (most recent call last):
File "/Users/user/EventFeed/hello.py", line 1, in <module>
from flask import Flask
ImportError: No module named flask
Textmate calls pythonw instead of python. When I try pythonw myself the same error is thrown.
The man pythonw states that As of Python 2.5, python and pythonw are interchangeable though they appear not to be in this case.
Would you have an idea of what happens?
(Question Code that works with python and not with pythonw does not answer the question despite its similar title.)
The problem is that your pythonw and your python are not pointing at the same Python installations.
Why?
Most likely because you've installed a second Python 2.7 that doesn't include the obsolete pythonw, but Apple's pre-installed Python 2.7 definitely does include it.
The quickest way to check this is the which command. For example, on one of my machines:
$ which python
/usr/local/bin/python
$ which pythonw
/usr/bin/pythonw
That first one is a symlink to a Homebrew install of Python 2.7, while the second is Apple's Python 2.7. Your exact details may differ; the first one may be a symlink to /Library/Frameworks/Python.framework/Versions/2.7/bin/python, or a wrapper executable that actually lives in /usr/local/bin, or it may be in /opt/local, etc. The point is that they're not in the same directories.
At any rate, your two separate installations of Python don't share the same site-packages (and they shouldn't), so the fact that you've installed Flask for the second one doesn't help the Apple one. You can verify this by running them and printing out sys.path:
$ python
>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.7/site-packages', …]
>>> ^D
$ pythonw
>>> import sys
>>> sys.path
['', '/Library/Python/2.7/site-packages', …]
>>> ^D
Anyway, the simplest solution is to configure your editor to run python instead of pythonw—or, better, give it an absolute path to a Python interpreter like /usr/local/bin/python2.7 to make absolutely sure you know what you're running.
(I don't know TextMate very well, but from this source it looks like it has a setting named TM_PYTHON that should control this…)
I'm quite new to python and just created my first opensource python project - a daemon to create wifi hotspots on linux.
I've used distutils to build the package. To start the daemon once installation is done, I've registered the below script that simply starts the daemon by calling the corresponding python module:
#!/bin/bash
python -m hotspotd $*
And this is the setup.py that registers it:
#INSTALL IT
from distutils.core import setup
s = setup(name='hotspotd',
version='0.1',
description='Small daemon to create a wifi hotspot on linux',
license='MIT',
author='Prahlad Yeri',
author_email='prahladyeri#yahoo.com',
url='https://github.com/prahladyeri/hotspotd',
#py_modules=['hotspotd','cli'],
packages=['hotspotd'],
package_dir={'hotspotd': ''},
package_data={'hotspotd': ['run.dat']},
scripts=['hotspotd']
#data_files=[('config',['run.dat'])],
)
Now, this works fine on my machine and some other machines I've tested. However, as indicated by the open issue on the github, some users are unable to run that script. It gives the error:
No module named hotspotd.main; 'hotspotd' is a package and cannot be directly executed
Apparently it expects the entire package.module syntax which is hotspotd.hotspotd on their setups. However, on my machine the full syntax doesn't work, and only hotspotd works. Whats going on here?
I had to change my script, so that instead of directly passing the module as argument, I import this module in the script itself and call the hotspotd.main function from there:
#!/usr/bin/env python
##author: Prahlad Yeri
##description: Small daemon to create a wifi hotspot on linux
##license: MIT
#python -m hotspotd $*
import hotspotd.main
import sys
import os
import argparse
if __name__ == "__main__":
#check root or not
if os.getenv('USER') != 'root':
print "You need root permissions to do this, sloth!"
sys.exit(1)
parser = argparse.ArgumentParser(description='A small daemon to create a wifi hotspot on linux')
parser.add_argument('-v', '--verbose', required=False, action='store_true')
parser.add_argument('command', choices=['start', 'stop', 'configure'])
args = parser.parse_args()
hotspotd.main.main(args)