Python script to process subtitles by jojolafrite not working - python

This script was posted on the interweb to insert 'silence lines' in a .srt subtitles file so that subtitles don't stay on too long, as indicated.
I can't figure out how to pass the subtitle file name; always get:
"type error: unsupported operand type(s) for %: 'NonType' and 'tuple'"
when I run with a file name after the module or
"Please provide subtitle file to process"
from the code if I don't. Is the code faulty of am I making a stupid error? Cheers.
#! /usr/bin/python
import sys;
# Patching SRT files to make them readable on Samsung TVs
# It basically inserts blank subtitles when silence should occur.
seqNo=1
try:
subs = open(sys.argv[1])
except:
print "Please provide subtitle file to process"
sys.exit(1)
while True:
srtSeqNo=subs.readline();
try:
begin,arrow,end=subs.readline().rstrip('\n\r').split(" ")
except:
break
srtText = subs.readline();
again = subs.readline();
while len(again.strip('\n\r')) > 0:
srtText = srtText + again
again = subs.readline()
print "%d\n%s --> %s\n%s" % (seqNo, begin, end, srtText)
seqNo = seqNo + 1
print "%d\n%s --> %s\n%s\n" % (seqNo, end, end, " ")
seqNo = seqNo + 1

Look after the sys.argv.
You must execute the script with the the full qualified path of your SRT file as an argument. Something like:
python script.py /home/user/folder/foo.srt

The script is functioning properly. This worked for me:
python main.py torchwood.srt
Here, my torchwood.srt file was in the same directory where the main.py file was. You can use full path of the subtitle file if it's not in the same directory.
You must pass an existing .srt file with valid contents. If the file is not found or can not be opened, it will display "Please provide subtitle file to process". So check file path and file permissions too.

Related

How to fix "Tail: Write Error: Broken Pipe" in running linux command in Python?

I am trying to print line-by-line per file that is inside a list.
At the end of each line of the file, it needs to check if the term ".sh" is in it or not.
I am getting the error
"Tail: Write error: "Broken Pipe"
Expected result:
Read each from list
Check each line of the file if the term ".sh" comes in it at the end of the line of the file.
Prints if it finds the ".sh"
This is what I have atm:
# Modules
import os
from pprint import pprint
# Files in list
dirlist = ['test.txt','test2.txt','test3.txt']
# Loop to read the file in list
for x in range (len(dirlist)):
print ("Output of Filename: " + dirlist[x]
# Variable to save the last 3 characters of the line
last3 = os.popen ("cat " + dirlist[x] + " | tail -c 3")
print last3
# Read file
f = open(dirlist[x], "r")
# Loop to check if the keyword is the same as last3
for l in f:
if last3 in l:
print ("FOUND IT!")
else:
print ("NOT IN IT!")
Outcome:
#Nic
[![enter image description here][3]][3]
I suggest that you use with environment with native python code instead of open and os.popen
Here is an example
# Files in list
dirlist = ['test.txt','test2.txt','test3.txt']
# Loop to read the file in list
for x in dirlist:
print ("Output of Filename: " + x)
with open(x) as f
lines=f.readlines()
for line in lines: #here you print each line
print (line)
if '.sh' in lines[-1:]: #check if .sh is in the last line
print("found it")
else:
print("didnt find it")
os.popen returns a file object, not a string.
See: Assign output of os.system to a variable and prevent it from being displayed on the screen
tail (actually stdio) gives the "Broken Pipe" error when it tries to write output but there's nobody around to read it. (More specifically, when it receives SIGPIPE.)
If you're going to launch a child process with popen, you need to finish reading from the pipe before your program exits.
In your case, you should probably use subprocess.run rather than a bare os.popen.
Or, better yet, don't use a subprocess for simple file operations! Just do them in native Python code, and it will be much simpler.
With the help Of #Nic Wanavit and Daniel Pyrden, I finally fixed it.
I've put the if/else inside the loop, otherwise it would check all the lines for the .sh instead of per line.
and I've put parenthesis inside the ".sh" section and that worked!
However, I did not do it in the last 3 characters, because the -1: wasn't working for me for some reason.
# Files in List
dirlist = ['test.txt', 'test2.txt', 'test3.txt']
# Loop to read the file in list
for x in dirlist:
print ("Output of filename: "+ x)
with open(x) as f:
lines = f.readlines()
for line lines:
print ("Line in file: " + line)
if (".sh" in line):
print ("FOUND IT")
else:
print ("not found it \n")
Result

Reading a file content does not raise exception if the file is not present

I am trying to read a file as follows and I want to log an error if the file does not exist. So I wrote the following code. But this code does not go into the except block at all. I don't have the file for sure.
DEFAULT_ROLE_PROPERTIES = '/tmp/role.properties'
try:
self.role_properties = os.environ.get('VAULT_ROLE_PROPERTIES', DEFAULT_ROLE_PROPERTIES)
with open(self.role_properties, 'r') as rolefp:
cfg.readfp(rolefp)
self.role_id = cfg.get('region', 'role_id')
except Exception as msg:
self.log.error("Unable to read role properties")
I am not sure what is wrong with the syntax here. The above code is in an init function (constructor) could that be the issue?
ls /tmp/role.properties
ls: cannot access /tmp/role.properties: No such file or directory
You could use os.path to check that the path exists (first) before proceeding with getting environment/other attributes
Sample code:
import os.path
os.path.exists('tmp/role.properties/')
If you were checking to see if a particular file was present, and valid (not empty) you could use os.stat
try:
if os.stat(filename).st_size > 0:
print "file present"
else:
print "file present but empty"
except OSError:
print "No file"
Hope this helps

User input path not recognised by os.path.abspath

I am writing a script in which I want the user to input a file path that will then be parsed by the rest of the script as a way to know which file to work on.
For brevity here is the beginning of the code which is where I have a problem:
### import modules
import pyabf
#### open file and extract basic data
file_path = input('file path?')
abf = pyabf.ABF(file_path)
data = abf.data
If I run the script in this form I get the following error:
File "/Users/XXX/anaconda3/envs/blah_blah/lib/python3.6/site-packages/pyabf/abf.py", line 65, in init
raise ValueError("ABF file does not exist: %s" % self.abfFilePath)
ValueError: ABF file does not exist
And here the portion of the script that gives me this error:
# clean-up file paths and filenames, then open the file
self.abfFilePath = os.path.abspath(abfFilePath)
if not os.path.exists(self.abfFilePath):
raise ValueError("ABF file does not exist: %s" % self.abfFilePath)
self.abfID = os.path.splitext(os.path.basename(self.abfFilePath))[0]
log.debug(self.__repr__())
If I run the lines of the code individually in the console everything works:
abf = pyabf.ABF(file_path) # same path as before works to open the file
data = abf.data # then manages to extract the correct numpy array.
What happens to the path when it is fed into as user input as opposed to being given directly into the argument where it will be used? I have tried to type the path in different ways with or without '' or () but I can't get it to be recognised by the pyabf.ABF script.
I had a look at the os.path info and from what I can understand the os.path.abspath(abfFilePath) line, which is bugging now, should just return an absolute path name. I'm sure it's probably something simple and obvious that I just don't get.
Hopefully someone here can help.
Thanks!

Why is exec() command running with no errors but not producing the expected output?

I'm creating a very basic python program that allows a user to enter a command that is then ran as code.
For example I have imported a file called textScripts.py: within that file there is a function called createFile(). When the user enters textScripts.createFile() it is passed into exec(). It runs without error and exits the program but the file isn't created!
I know the createFile() function works because if I put textScripts.createFile() in the code it creates a file.
Here is the relevant snippet of code:
commandList=[]
while(commandRun):
count = 0
commandList.append(input(">>>"))
exec(commandList[count])
print(commandList[count])
count += 1
here is a screenshot of the code being run:
>>> textScripts.createFile()
>>>
here is a screenshot of the folder:
__pyCache__
textScripts.py
CLIFile.py
there should be a file in this folder
here is the function createFile():
def createFile(
destination = os.path.dirname(__file__),
text = "Sick With the Python\n"
):
''' createFile(destination, text)
This script creates a text file at the
Specified location with a name based on date
'''
date = t.localtime(t.time())
name = "%d_%d_%d.txt" %(date[1], date[2], date[0])
if not(os.path.isfile(destination + name)):
f = open(destination + name, "w")
f.write( text )
f.close
else:
print("file already exists")
I apologize in advance if this is an obvious questions; I'm new to python and have been looking for hours for an answer as to why this happens.
You save file to wrong folder (you can insert "print(destination + name)" in your function)
You need to replace this:
destination + name
to this:
os.path.join(destination, name)
PS:
You don't close the file (f.close -> f.close())
The best way to open any resource is using "with".
For example:
with open('file.txt', 'w') as f:
f.write('line')

python mp3 meta-tag

I try to write a script than scan recursive a given directory and if found mp3 get and just print meta tag for it. What ever I passed to getEyeD3Tag I got an exception. Here is my code that i have written so far
def getEyeD3Tags(path):
try:
trackInfo = eyeD3.Mp3AudioFile(path)
tag = trackInfo.getTag()
tag.link(path)
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
#return (tag.getArtist(),tag.getTitle(),tag.getAlbum())
except eyeD3.InvalidAudioFormatException:
print "File %s is not a mp3 file " % path
mp3Num=0
temp=os.walk(valid-folder-name)
for root, dirs, files in temp:
for i in files:
if os.path.join(root,i):
temp=os.path.splitext(i)
temp[1].lower()
if temp[1]=='.mp3':
mp3Path=os.path.join(root,i)
print mp3Path
getEyeD3Tags(mp3Path)
mp3Num+=1
raw_input()
#print "**"
else:
print "Error invalid path"
print "\n\n"
#raw_input()
print mp3Num
raw_input()
And BTW is it a way to get genre of mp3 file using eyeD3?
Thx in advance
To check if the file being parsed is a valid mp3, call the eyeD3.isMp3File(filename) method.
The following is from a short script I made to auto-sort my music folder.
def parseIDETag(self, path):
if eyeD3.isMp3File(path):
That way, if the file isn't an mp3, it'll just skip over it.
Also, str(tag.getGenre()) returns the genre as a string using eyeD3.

Categories

Resources