Trying to create a shell script on a raspi3 in python to start a webcam. Getting a syntax error when trying to run the script.
Keep in mind I am new to Python but I have tried each individually to see what prints out, only getting this when I combine the script..
from gpiozero import Button
from pipes import quote
import time
import os
print("your script has started")
camOutput = 'output_http.so -w ./www'
camInput = 'input_raspicam.so -hf'
camStart = '/home/pi/projects/mjpg-streamer/mjpg_streamer -o'.format(quote(camOutput)).'-i'.format(quote(camInput))
print("your script is loaded")
stopButton = Button(26) #shutdown
camButton = Button(25) #web cam
ledButton = Button(24) #top led
while True:
if stopButton.is_pressed:
time.sleep(1)
if stopButton.is_pressed:
os.system("shutdown now -h")
time.sleep(1)
camStart = '/home/pi/projects/mjpg-streamer/mjpg_streamer -o'.format(quote(camOutput)).'-i'.format(quote(camInput))
^
SyntaxError: invalid syntax```
In Python, the dot operator is not used to concatenate strings, only to access properties and methods of an object. Thus, putting a string literal after a dot, such as .'-i', is a syntax error.
You probably want to do something like this, using the format method to replace the {} placeholders with the provided values:
camStart = '/..../mjpg_streamer -o {} -i {}'.format(quote(camOutput),quote(camInput))
Related
I am trying to convert audio into text using google cloud API. I am following their official documentaion but it keeps me giving an error
File "heyfinal.py", line 15
,requests,
^
SyntaxError: positional argument follows keyword argument
The link to documentation is: https://googleapis.github.io/google-cloud-python/latest/speech/index.html#streaming-recognition
import io
from google.cloud import speech
client = speech.SpeechClient()
config = speech.types.RecognitionConfig(
encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,
language_code='en-US',
sample_rate_hertz=44100,
)
with io.open('./rehan.wav', 'rb') as stream:
requests = [speech.types.StreamingRecognizeRequest(
audio_content=stream.read(),
)]
results = sample.streaming_recognize(
config=speech.types.StreamingRecognitionConfig(config=config)
,requests,
)
for result in results:
for alternative in result.alternatives:
print('=' * 20)
print('transcript: ' + alternative.transcript)
print('confidence: ' + str(alternative.confidence))
Some python versions might be more strict about syntax than others. Simply change it like this:
results = sample.streaming_recognize(
config=speech.types.StreamingRecognitionConfig(config=config),
requests=requests)
and it will work.
I am trying to test a number of Python 2.7 classes using unittest.
Here is the exception:
ScannerError: mapping values are not allowed here
in "<unicode string>", line 3, column 32:
... file1_with_path: '../../testdata/concat1.csv'
Here is the example the error message relates to:
class TestConcatTransform(unittest.TestCase):
def setUp(self):
filename1 = os.path.dirname(os.path.realpath(__file__)) + '/../../testdata/concat1.pkl'
self.df1 = pd.read_pickle(filename1)
filename2 = os.path.dirname(os.path.realpath(__file__)) + '/../../testdata/concat2.pkl'
self.df2 = pd.read_pickle(filename2)
self.yamlconfig = u'''
--- !ConcatTransform
file1_with_path: '../../testdata/concat1.csv'
file2_with_path: '../../testdata/concat2.csv'
skip_header_lines: [0]
duplicates: ['%allcolumns']
outtype: 'dataframe'
client: 'testdata'
addcolumn: []
'''
self.testconcat = yaml.load(self.yamlconfig)
What is the the problem?
Something not clear to me is that the directory structure I have is:
app
app/etl
app/tests
The ConcatTransform is in app/etl/concattransform.py and TestConcatTransform is in app/tests. I import ConcatTransform into the TestConcatTransform unittest with this import:
from app.etl import concattransform
How does PyYAML associate that class with the one defined in yamlconfig?
A YAML document can start with a document start marker ---, but that has to be at the beginning of a line, and yours is indented eight positions on the second line of the input. That causes the --- to be interpreted as the beginning of a multi-line plain (i.e. non-quoted) scalar, and within such a scalar you cannot have a : (colon + space). You can only have : in quoted scalars. And if your document does not have a mapping or sequence at the root level, as yours doesn't, the whole document can only consists of a single scalar.
If you want to keep your sources nicely indented like you have now, I recommend you use dedent from textwrap.
The following runs without error:
import ruamel.yaml
from textwrap import dedent
yaml_config = dedent(u'''\
--- !ConcatTransform
file1_with_path: '../../testdata/concat1.csv'
file2_with_path: '../../testdata/concat2.csv'
skip_header_lines: [0]
duplicates: ['%allcolumns']
outtype: 'dataframe'
client: 'testdata'
addcolumn: []
''')
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_config)
You should get into the habit to put the backslash (\) at the end of your first triple-quotes, so your YAML document. If you do that, your error would have actually indicated line 2 because the document doesn't start with an empty line anymore.
During loading the YAML parser encouncters the tag !ConcatTransform. A constructor for an object is probably registered with the PyYAML loader, associating that tag with the using PyYAML's add_constructor, during the import.
Unfortunately they registered their constructor with the default, non-safe, loader, which is not necessary, they could have registered with the SafeLoader, and thereby not force users to risk problems with non-controlled input.
i am working on 'wolframalpha' api and i am keep getting this error, i tried to search but not getting any working post on this error if you know please help me to fix this error
File "jal.py", line 9
app_id=’PR5756-H3EP749GGH'
^
SyntaxError: invalid syntax
please help; i have to show project tomorrow :(
my code is
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wolframalpha
import sys
app_id=’PR5756-H3EP749GGH'
client = wolframalpha.Client(app_id)
query = ‘ ‘.join(sys.argv[1:])
res = client.query(query)
if len(res.pods) > 0:
texts = “”
pod = res.pods[1]
if pod.text:
texts = pod.text
else:
texts = “I have no answer for that”
# to skip ascii character in case of error
texts = texts.encode(‘ascii’, ‘ignore’)
print texts
else:
print “Sorry, I am not sure.”
You used a backtick (´) instead of a single-quote (').
app_id='PR5756-H3EP749GGH'
Python directly shows you the error.
Also, use an editor with text highlighting.
On my system I currently running Polipo proxy, mainly for adblock purposes.
By a search on internet I've found many shell scripts to convert adblock plus lists in Polipo forbidden file format; most of these scripts rely on sed, ruby or python.
However none of them is able to generate a valid forbidden file: when I restart Polipo with the new generated forbidden file, in the Polipo's log file I see the message: "Couldn't compile regex: Unmatched ( or \("
The following python script which I attempt to use, is intended to convert an easylist file in a Polipo's forbidden file format:
#!/bin/python
# convert adblock ruleset into polipo-forbidden format
if __name__ == "__main__":
import os
import sys
import re
if len(sys.argv) == 1:
sys.exit("Usage: %s <adblockrules>" % os.path.basename(sys.argv[0]))
if not os.path.exists(sys.argv[1]):
sys.exit("The rules file (%s) doesn't exist" % sys.argv[1])
fhandle = file(sys.argv[1])
lines = fhandle.readlines()
fhandle.close()
dollar_re = re.compile("(.*?)\$.*")
for line in lines:
if line:
if (line[0] in ("[", "!", "~", "#", "#") or
line.startswith("/adverti") or
"##" in line):
continue
line = dollar_re.sub(r"\1", line)
# line = line.replace("|http://", "")
line = line.replace("|", "")
line = line.replace("||", "")
line = line.replace(".", r"\.")
line = line.replace("*", ".*")
line = line.replace("?", r"\?")
line = line.replace("^", r"[\/:\.=&\?\+\-\ ]+")
# line = line.replace("&", r"\&")
# line = line.replace("+", r"\+")
# line = line.replace("-", r"\-")
# line = line.replace(";", r"\;")
# line = line.replace("=", r"\=")
# line = line.replace("/", r"\/")
print(line.strip())
print("")
But as I've said, when I actualize this forbidden file, Polipo will claim "Couldn't compile regex: Unmatched ( or \("
This one is the forbidden file generated by the script
http://wikisend.com/download/494664/forbidden.conf
As I've said, online, there are many scripts like the one which I use, some of them also relies on sed, but no one seems able to generate a valid forbidden file (Polipo will always claims "Couldn't compile regex").
This is not a Polipo's fault, because if I made a clean forbidden file with some web url inside, Polipo will properly block these connections.
Can someone help me and explain how to modify/make a proper script to convert adblock lists in a valid regex forbidden file for Polipo?
Many thanks.
You can convert an Adblock rule to a Python regex using https://github.com/scrapinghub/adblockparser library:
>>> from adblockparser import AdblockRule
>>> rule = AdblockRule("/ad/loaders/*")
>>> print(rule.regex)
/ad/loaders/.*
I'm not sure Polipo suports the same regex format though; regexes can get pretty hairy:
>>> print(AdblockRule("||example.com$").regex)
^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?example\.com
Also take care of rules with options; it may be better to remove them because semantics is different.
Hope this helps.
I am trying to implement a hash function and here is my code:
import BitVector
import glob
path = '/home/vguda/Desktop/.txt'
files=glob.glob(path)
hash = BitVector.BitVector(size = 32)
hash.reset(0)
i = 0
for file in files:
bv = BitVector.BitVector( filename = file )
while 1 :
bv1 = bv.read_bits_from_file(8)
if str(bv1) == "":
break
hash[0:8] = bv1 ^ hash[0:8]
hash >> 8
i = i+1
hash_str = ""
hash_str = str( hash )
text_file = open("/home/vguda/Desktop/result.txt ","w")
text_file.write("Hash Code is %s" %hash_str)
text_file.close()
print hash
print (i)
The displayed error is:
"bash: syntax error near unexpected token `('
First, perhaps this happened in copy and paste, but your indenting in your loop is all messed up, I'm not sure which blocks go where.
When you run things in the shell, you need to either tell python to run it:
python myscript.py
Or, put the following line as the first thing in your program to tell bash to run it as a python program:
#!/usr/bin/python
Currently, bash is trying to run your python program as a bash script, and obviously running into syntax errors.