Python Forum
Adding a parameter/argument to a script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding a parameter/argument to a script
#1
Have been running tests with small WAV files, and need to remove the hard code reference to a WAV file and add a parameter. Here is the code:

#!/usr/bin/env python3

import speech_recognition as sr

# obtain path to "english.wav" in the same folder as this script
from os import path
AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "english.wav")
# AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "french.aiff")
# AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "chinese.flac")

# use the audio file as the audio source
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
    audio = r.record(source)  # read the entire audio file

# recognize speech using Sphinx
try:
    print("Sphinx thinks you said " + r.recognize_sphinx(audio))
except sr.UnknownValueError:
    print("Sphinx could not understand audio")
except sr.RequestError as e:
    print("Sphinx error; {0}".format(e))
From another script, I can see by the code at the bottom, how to determine if any arguments are present. I'm just not too sure how to use similar code and not have the WAV file hard coded. Needs to be parsed as an argument/parameter. Here is that other code snippet:

def main(args):
    if len(args) != 2:
        sys.stderr.write(
            'Usage: example.py <aggressiveness> <path to wav file>\n')
        sys.exit(1)
    audio, sample_rate = read_wave(args[1])
    vad = webrtcvad.Vad(int(args[0]))
    frames = frame_generator(30, audio, sample_rate)
    frames = list(frames)
    segments = vad_collector(sample_rate, 30, 300, vad, frames)
    for i, segment in enumerate(segments):
        path = 'chunk-%002d.wav' % (i,)
        print(' Writing %s' % (path,))
        write_wave(path, segment, sample_rate)


if __name__ == '__main__':
    main(sys.argv[1:])
Reply
#2
Support, you have a param '--filename'. Than you can get its value this way:

import sys
print sys.argv[sys.argv.index('--filename') + 1]
If you run python script.py --filename name.wav it prints name.wav.
jehoshua likes this post
Reply
#3
(Jan-28-2018, 03:56 AM)egslava Wrote: Support, you have a param '--filename'. Than you can get its value this way:

import sys
print sys.argv[sys.argv.index('--filename') + 1]
If you run python script.py --filename name.wav it prints name.wav.

Thanks, and if I run in python2 it's okay, but in python3, it gives an error

Quote: print sys.argv[sys.argv.index('--filename') + 1]
^
SyntaxError: invalid syntax

Python3 = 3.5.2
Python2 = 2.7.12
Reply
#4
The simplest way is to use module argparse from the standard library. It's only a few lines of code, and there is great benefit for your future scripts.
jehoshua likes this post
Reply
#5
(Jan-28-2018, 05:43 AM)Gribouillis Wrote: The simplest way is to use module argparse from the standard library. It's only a few lines of code, and there is great benefit for your future scripts.

Thanks, I was just looking at https://docs.python.org/3/howto/argparse.html
Reply
#6
A couple of alternatives,a demo with Click and Fire.
jehoshua likes this post
Reply
#7
(Jan-28-2018, 05:43 AM)jehoshua Wrote: ...
if I run in python2 it's okay, but in python3, it gives an error
...

It's ok, just for python 3 you need to use braces:


import sys
print ( sys.argv[sys.argv.index('--filename') + 1] )
I don't have python 3 now to check it, so I'd appreciate if you tell me whether it works in Python 3 :)
jehoshua likes this post
Reply
#8
(Jan-28-2018, 06:14 AM)snippsat Wrote: A couple of alternatives,a demo with Click and Fire.
I like argh, but for simple scripts such as this one, the built-in argparse module works very well.
Reply
#9
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('filename', type=argparse.FileType('br'), help='File name') # open the directly for reading
# parser.add_argument('filename', help='File name') # or just as an argument

args = parser.parse_args()

while True:
    chunk = args.filename.read(4096) # it is opened for reading already by argparse

    if chunk:
        # do something
    else:
        break

## if it is just an argument
# with open(args.filename, 'br') as in_file:
    # read it
    # do something
This will make the file name argument mandatory.
The good thing? You have a help system so you could just:

$ script.py -h

It works even if you miss the 'help' argument while adding the argument to the parser.
Or if you miss the argument it will throw the proper message.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#10
(Jan-28-2018, 06:14 AM)snippsat Wrote: A couple of alternatives,a demo with Click and Fire.

Thanks, I will keep that in mind. :)

(Jan-28-2018, 06:42 AM)egslava Wrote: I don't have python 3 now to check it, so I'd appreciate if you tell me whether it works in Python 3 :)

#!/usr/bin/env python3

import sys

print ( sys.argv[sys.argv.index('--filename') + 1] )
Output:
$ python3 test3.py Traceback (most recent call last): File "test3.py", line 5, in <module> print ( sys.argv[sys.argv.index('--filename') + 1] ) ValueError: '--filename' is not in list $ python3 test3.py output3.wav Traceback (most recent call last): File "test3.py", line 5, in <module> print ( sys.argv[sys.argv.index('--filename') + 1] ) ValueError: '--filename' is not in list $ python3 test3.py --filename output3.wav output3.wav
(Jan-28-2018, 08:48 AM)wavic Wrote:
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('filename', type=argparse.FileType('br'), help='File name') # open the directly for reading
# parser.add_argument('filename', help='File name') # or just as an argument

args = parser.parse_args()

while True:
    chunk = args.filename.read(4096) # it is opened for reading already by argparse

    if chunk:
        # do something
    else:
        break

## if it is just an argument
# with open(args.filename, 'br') as in_file:
    # read it
    # do something
This will make the file name argument mandatory.
The good thing? You have a help system so you could just:

$ script.py -h

It works even if you miss the 'help' argument while adding the argument to the parser.
Or if you miss the argument it will throw the proper message.

Thanks for the argparse example. I have modified it to include the code for speech recognition

#!/usr/bin/env python3

import argparse
import speech_recognition as sr
import sys

parser = argparse.ArgumentParser()
 
parser.add_argument('filename', type=argparse.FileType('br'), help='File name') # open the directly for reading
# parser.add_argument('filename', help='File name') # or just as an argument
 
args = parser.parse_args()
 
while True:
    #print ( sys.argv[sys.argv.index('--filename') + 1] )
    print("The audio filename is %s." % args.filename)
    chunk = args.filename.read(4096) # it is opened for reading already by argparse
    AUDIO_FILE = args.filename
    
    if chunk:
        # use the audio file as the audio source
        r = sr.Recognizer()
        with sr.AudioFile(AUDIO_FILE) as source:
            audio = r.record(source)  # read the entire audio file

        # recognize speech using Sphinx
        try:
            print("Sphinx thinks you said " + r.recognize_sphinx(audio))
        except sr.UnknownValueError:
            print("Sphinx could not understand audio")
        except sr.RequestError as e:
            print("Sphinx error; {0}".format(e))
  
    else:
        break
 
## if it is just an argument
# with open(args.filename, 'br') as in_file:
    # read it
    # do something
The help works fine

Output:
$ python3 test2.py -h usage: test2.py [-h] filename positional arguments: filename File name optional arguments: -h, --help show this help message and exit
when I ran that test script, there were many errors, but I feel 99% of them are because the filename is not being evaluated correctly. (Most of the errors came from the speech recognition side of things).

Output:
$ python3 test2.py output3.wav The audio filename is <_io.BufferedReader name='output3.wav'>. Traceback (most recent call last): File "/home/********/.local/lib/python3.5/site-packages/speech_recognition/__init__.py", line 203, in __enter__ self.audio_reader = wave.open(self.filename_or_fileobject, "rb") File "/usr/lib/python3.5/wave.py", line 499, in open return Wave_read(f) File "/usr/lib/python3.5/wave.py", line 163, in __init__ self.initfp(f) File "/usr/lib/python3.5/wave.py", line 130, in initfp raise Error('file does not start with RIFF id') wave.Error: file does not start with RIFF id During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/********/.local/lib/python3.5/site-packages/speech_recognition/__init__.py", line 208, in __enter__ self.audio_reader = aifc.open(self.filename_or_fileobject, "rb") File "/usr/lib/python3.5/aifc.py", line 890, in open return Aifc_read(f) File "/usr/lib/python3.5/aifc.py", line 340, in __init__ self.initfp(f) File "/usr/lib/python3.5/aifc.py", line 305, in initfp raise Error('file does not start with FORM id') aifc.Error: file does not start with FORM id During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/********/.local/lib/python3.5/site-packages/speech_recognition/__init__.py", line 234, in __enter__ self.audio_reader = aifc.open(aiff_file, "rb") File "/usr/lib/python3.5/aifc.py", line 890, in open return Aifc_read(f) File "/usr/lib/python3.5/aifc.py", line 340, in __init__ self.initfp(f) File "/usr/lib/python3.5/aifc.py", line 303, in initfp chunk = Chunk(file) File "/usr/lib/python3.5/chunk.py", line 63, in __init__ raise EOFError EOFError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test2.py", line 23, in <module> with sr.AudioFile(AUDIO_FILE) as source: File "/home/********/.local/lib/python3.5/site-packages/speech_recognition/__init__.py", line 236, in __enter__ raise ValueError("Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format") ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format
Have done a fair bit of looking at other examples of argparse, but still not able to get the variable args.filename evaluated properly. Yet the one liner with using the sys module works okay.

Hmm, I changed 2 instances of "args.filename" to "args.filename.name" , and it works.

#!/usr/bin/env python3

import argparse
import speech_recognition as sr
import sys

parser = argparse.ArgumentParser()
 
parser.add_argument('filename', type=argparse.FileType('br'), help='File name') # open the directly for reading
# parser.add_argument('filename', help='File name') # or just as an argument
 
args = parser.parse_args()
 
while True:
    #print ( sys.argv[sys.argv.index('--filename') + 1] )
    print("The audio filename is %s." % args.filename.name)
    chunk = args.filename.read(4096) # it is opened for reading already by argparse
    AUDIO_FILE = args.filename.name
    
    if chunk:
        # use the audio file as the audio source
        r = sr.Recognizer()
        with sr.AudioFile(AUDIO_FILE) as source:
            audio = r.record(source)  # read the entire audio file

        # recognize speech using Sphinx
        try:
            print("Sphinx thinks you said " + r.recognize_sphinx(audio))
        except sr.UnknownValueError:
            print("Sphinx could not understand audio")
        except sr.RequestError as e:
            print("Sphinx error; {0}".format(e))
  
    else:
        break
 
## if it is just an argument
# with open(args.filename, 'br') as in_file:
    # read it
    # do something
but it is stuck in a loop, ..lol. I will see about the 'while' maybe. :)

No loop now, and removed some code, ..short and simple

#!/usr/bin/env python3

import argparse
import speech_recognition as sr

parser = argparse.ArgumentParser()
parser.add_argument('filename', type=argparse.FileType('br'), help='File name') # open the directly for reading
args = parser.parse_args()
 
print("The audio filename is %s." % args.filename.name)
AUDIO_FILE = args.filename.name
    
# use the audio file as the audio source
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
    audio = r.record(source)  # read the entire audio file

# recognize speech using Sphinx
try:
    print("Sphinx thinks you said " + r.recognize_sphinx(audio))
except sr.UnknownValueError:
    print("Sphinx could not understand audio")
except sr.RequestError as e:
    print("Sphinx error; {0}".format(e))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [ERROR] ParamValidationError: Parameter validation failed: Invalid type for parameter gdbengo 3 10,977 Dec-26-2022, 08:48 AM
Last Post: ibreeden
  Adding a Wake word to my Script Extra 9 3,089 Jan-16-2022, 10:46 AM
Last Post: SheeppOSU
  Adding a list to Python Emailing Script Cknutson575 4 2,305 Feb-18-2021, 09:13 AM
Last Post: buran
  SyntaxError: positional argument follows keyword argument syd_jat 3 5,822 Mar-03-2020, 08:34 AM
Last Post: buran
  Adding markers to Folium map only adding last element. tantony 0 2,121 Oct-16-2019, 03:28 PM
Last Post: tantony
  Help needed adding a certain Argument StrongHandsDeepPockets 3 3,679 Apr-29-2018, 05:57 PM
Last Post: j.crater
  help with a script to determine length of an argument roadrage 9 8,465 Nov-02-2016, 06:02 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020