Running Python script through command, Syntax Error - python-2.7

I use a Raspberry Pi 3, and I'm trying to run this Python script through the command terminal:
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
Motor1A = 16
Motor1B = 18
Motor1E = 22
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)
print "Turning motor on"
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(2)
print "Stopping motor"
GPIO.output(Motor1E,GPIO.LOW)
GPIO.cleanup()
The file is called "motor1.py". It is located in the "/home/pi" directory.
When I type sudo python motor1.py, the terminal responds like so:
pi#raspberrypi:~ $ sudo python motor1.py
File "motor.py", line 1
Python 2.7.9 (default, Sep 17 2016, 20:26:04)
^
SyntaxError: invalid syntax
Can anyone tell me why? Thank a lot.
Johnny

Related

Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1 on AWS-EMR but works on local machine

I am trying to run a simple mapreduce code just to read using mapper.py, taking the output of mapper.py and reading by reducer.py. This code works on local computer but when I tried on aws-emr, it gives the following error -
Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
Here is the input.txt, mapper.py and reducer.py
input.txt
scott,haris
jenifer,smith
ted,brandy
amanda,woods
bob,wilton
damn,halloween
mapper.py
#!/usr/bin/env python
import sys
for line in sys.stdin:
x = line.strip()
first,last = x.split(",")
print '%s\t%s' % (first, last)
reducer.py
#!/usr/bin/env python
import sys
for line in sys.stdin:
x = line.strip()
key, value = x.split('\t')
print '%s\t%s' % (key, value)
I am using the following command:
hadoop jar /usr/lib/hadoop/hadoop-streaming.jar -files s3://test/mapper.py,s3://test/reducer.py -mapper "python mapper.py" -reducer "python reducer.py" -input s3://test/input.txt -output s3://test/output
It seems like you have problem with python reducer / mapper script, can you check two things below
1.Are your Mapper and Reducer scripts executable(make sure you are pointing to right env with , like try #!/usr/bin/python ) and have right permissions?
2.Your Python program is right, for example if server is running python3, you need to have brackets for print() or any other issue with the script.
Try to execute python normally in emr with bash and see if it works

Error Import Parquet in Windows

I'm trying to install Parquet file format to use it with Apache Spark. I learned that I had to install Thrift, ThriftPy, and Python-Snappy in order to fully install Parquet.
I install Thrift using the command
pip install thrift
Then I installed python-snappy manually through a wheel file found here. This was because I was unable to install python-snappy automatically. Anyways, python-snappy was successfully installed.
I also installed ThrifPy using the similar command
pip install ThriftPy
And finally, I used pip to install parquet which was successful. After installing, when I try to import parquet, it raises the error as
---------------------------------------------------------------------------
ThriftParserError Traceback (most recent call last)
<ipython-input-55-942008defa53> in <module>()
----> 1 import parquet
C:\anaconda2\lib\site-packages\parquet\__init__.py in <module>()
17 from thriftpy.protocol.compact import TCompactProtocolFactory
18
---> 19 from . import encoding
20 from . import schema
21 from .converted_types import convert_column
C:\anaconda2\lib\site-packages\parquet\encoding.py in <module>()
17
18 THRIFT_FILE = os.path.join(os.path.dirname(__file__), "parquet.thrift")
---> 19 parquet_thrift = thriftpy.load(THRIFT_FILE,
module_name=str("parquet_thrift")) # pylint: disable=invalid-name
20
21 logger = logging.getLogger("parquet") # pylint: disable=invalid-name
C:\anaconda2\lib\site-packages\thriftpy\parser\__init__.pyc in load(path,
module_name, include_dirs, include_dir)
28 real_module = bool(module_name)
29 thrift = parse(path, module_name, include_dirs=include_dirs,
---> 30 include_dir=include_dir)
31
32 if real_module:
C:\anaconda2\lib\site-packages\thriftpy\parser\parser.pyc in parse(path,
module_name, include_dirs, include_dir, lexer, parser, enable_cache)
494 raise ThriftParserError('ThriftPy does not support generating
module '
495 'with path in protocol \'{}\''.format(
--> 496 url_scheme))
497
498 if module_name is not None and not module_name.endswith('_thrift'):
ThriftParserError: ThriftPy does not support generating module with path in
protocol 'c'
Would someone tell me what I'm doing wrong ?
For reference, I'm using anaconda Python 2.7 on a Jupyter notebook. My OS is Windows 7 , and I'm using Spark on a single cluster.
Modify the parser code in the windows side. It is in site-packages of python.
For Example:- C:\Anaconda\python27\Lib\site-packages\thriftpy\parser\parser.py
Modify the 488 line:
#if url_scheme == '':
if len(url_scheme) <= 1:
Then try again.

Python 2: Type error "only integer scalar arrays can be converted to a scalar index" using pd.read() with neo.Spike2IO

I have code to load in Spike2 .smr files and read them in Jupyter. My code was working fine 2 days ago and now, with absolutely no change on either the file that is loaded in or the code that loads it in, it is not working. The problem code is as follows...
Cell 1 Input (to show the versions of my packages):
import sys
print("Python version: {}\n\nPackages versions: ".format(sys.version))
# which package versions are installed?
import pip
all_packages = pip.get_installed_distributions()
used_packages = ["matplotlib", "neo", "numpy", "OpenElectrophy", "os", "pandas",
"pylab", "scipy"]
for entry in used_packages:
for p in all_packages:
if entry in str(p):
print(str(p))
Cell 1 Output:
Python version: 2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
Packages versions:
matplotlib 1.4.3
matplotlib-venn 0.11.3
neo 0.3.3
numpy 1.12.0
pycosat 0.6.1
nose 1.3.7
backports.ssl-match-hostname 3.5.0.1
pandas 0.19.2
scipy 0.15.1
Cell 2 Input (load in my modules):
import pylab
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats as st
import os
import tables
import neo
import scipy.signal as sg
from scipy import interpolate as inter
import h5py as h
import quantities as q
plt.style.use('ggplot')
pd.options.display.max_rows = 999
%matplotlib inline
Now, I load in the Spike2 .smr file with:
r = neo.Spike2IO("Rawdata/143-16/nerve.smr").read()[0]
and get the following type error:
TypeError Traceback (most recent call last)
<ipython-input-3-f81fd520a4c5> in <module>()
----> 1 r = neo.Spike2IO("Rawdata/143-16/nerve.smr").read()[0]
/home/wolverine/anaconda/lib/python2.7/site-packages/neo/io/baseio.pyc in read(self, lazy, cascade, **kargs)
107 if not cascade:
108 return bl
--> 109 seg = self.read_segment(lazy=lazy, cascade=cascade, **kargs)
110 bl.segments.append(seg)
111 create_many_to_one_relationship(bl)
/home/wolverine/anaconda/lib/python2.7/site-packages/neo/io/spike2io.pyc in read_segment(self, take_ideal_sampling_rate, lazy, cascade)
120 if channelHeader.kind in [1, 9]:
121 #~ print 'analogChanel'
--> 122 anaSigs = self.readOneChannelContinuous( fid, i, header, take_ideal_sampling_rate, lazy = lazy)
123 #~ print 'nb sigs', len(anaSigs) , ' sizes : ',
124 for anaSig in anaSigs :
/home/wolverine/anaconda/lib/python2.7/site-packages/neo/io/spike2io.pyc in readOneChannelContinuous(self, fid, channel_num, header, take_ideal_sampling_rate, lazy)
240
241 anaSigs = [ ]
--> 242 if channelHeader.unit in unit_convert:
243 unit = pq.Quantity(1, unit_convert[channelHeader.unit] )
244 else:
/home/wolverine/anaconda/lib/python2.7/site-packages/neo/io/spike2io.pyc in __getattr__(self, name)
444 else:
445 l = np.fromstring(self.array[name][0], 'u1')
--> 446 return self.array[name][1:l+1]
447 else:
448 return self.array[name]
TypeError: only integer scalar arrays can be converted to a scalar index
The "neo.Spike2IO("filename.smr") works fine, but as soon as I add the "read()[0]" part, that is when I get the TypeError. I read up on this type error and the only answers I saw were that the file could be corrupt. I deleted my local file and re-downloaded it and also downloaded another similar file just in case the master file for the other one was corrupt. I retried my code on these two new files and received the Type Error code for both. As stated before, the code was working flawlessly just two days ago and now it won't load any .smr file. I went through and updated all of my modules and pip and anaconda, all of this did not help.
Here is a link to a short sample .smr file (only 3.1 MB) that I cut for sharing purposes. It also gives the Type Error. Any ideas? Thank you.
I solved this issue by further updating my modules and Anaconda itself (and all of its respective modules). Something must have reverted to an older version.
The code to update every package in Anaconda is:
conda update --all
Further help can be found here at the Conda homepage. Shutting down, then restarting your computer can also help to ensure that all of these updates are implemented.

Issue with importError: no module named BaseHTTPServer

Learning Python 2.7 and trying to run it on Vagrant.
Steps taken:
Vagrant up
Vagrant ssh
Run command python webserver.py
Issue when I run this command, it gives out an ImportError: No module named BaseHTTPServer. Is this problem related to pg_config.sh? Thank you in advance for helping me understand.
I have checked my python 2.7 directory. BaseHTTPServer.py seems to be there.
from BaseHTTPServer import BaseHTTPRequestHandler, BaseHTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_Get(self):
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_header()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print message
return
else:
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print "Web Server running on port %s" % port
server.serveforever()
except KeyboardInterrupt:
print " ^C entered, stopping web server...."
server.socket.close()
if _name_ == '__main__':
main()
You may consider switching to python 3.x. This is the updated version of your code in Python 3.7.2. Notice in the code below that the BaseHTTPServer module is changed to http.server in python3 link
from http.server import BaseHTTPRequestHandler, HTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print (message)
return
else:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print ("Web Server running on port %s" % port)
server.serve_forever()
except KeyboardInterrupt:
print (" ^C entered, stopping web server....")
server.socket.close()
if __name__ == '__main__':
main()
You can follow the link I provided above to read more from the documentation.
Are you sure that the python you are running/testing from the command line is the same python that your script is running?
i.e. BaseHTTPServer might be present in one install, but not the other.
For example, on my machine:
$ which python2.7
/usr/bin/python2.7
Is your "python" (in the command line you specified) the same as "python2.7"?
$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import BaseHTTPServer
>>> BaseHTTPServer
<module 'BaseHTTPServer' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.pyc'>
Try a module that does exist to ensure the path is what you are expecting.
In python earlier than v3 you need to run http server as
python -m SimpleHTTPServer 8069
if you are using pycharm, change the interpreter to Python 2.7 from the latest version.
If the project Interpreter is not present you can also add one by specifying the python 2.7 install path.

maya python subprocess error

in python 2.7 i try this code to get data from Deadline software. Its return some data from server...
import subprocess
path = 'C:/Program Files/Thinkbox/Deadline7/bin/'
p1 = subprocess.Popen([path + 'deadlinecommand.exe', 'pools'], stdout=subprocess.PIPE)
p1.communicate()
and see result:
('none\r\npool_01\r\npool_02\r\npool_03\r\npool_04\r\npool_05\r\npoolhalf\r\n', None)
but when i copy that code to python in maya 2014 i get error:
p1 = subprocess.Popen(['path + 'deadlinecommand.exe', 'pools'], stdout=subprocess.PIPE)
# Error: WindowsError: file C:\PROGRA~1\Autodesk\maya2014\bin\python27.zip\subprocess.py line 826: 6 #
run this exe file - is the only option dedline communication. but it pays to stdout data and how it is necessary to pull out. subprocess options except I have not found, but if there are other options will be glad to try them
anyone else encountered this problem? strange that in pure Python 2.7 running in windows all works, and there is no Maya 2014
i use:
Windows 7 + Python 2.7.9
Maya 2014 (Python 2.7.3)
I was just trying something similar couple of days back, connecting to Deadline via the command line submitter and getting
# File "C:\Program Files\Autodesk\Maya2013\bin\python26.zip\subprocess.py", line 786, in _make_inheritable
# WindowsError: [Error 6] The handle is invalid
error in Maya 2013.5. One workaround found here which does fix this issue is to pipe all the handles
p1 = subprocess.Popen([path + 'deadlinecommand.exe', 'pools'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Hope it helps.