How to compress a video using ffmpeg in python? - python-3.x

I made this script for compressing videos in Python 3:
import os
import sys
import subprocess
result = subprocess.run('ffmpeg -i output.mp4 -b 800k output.mp4')
print(result)
When I run the above, some error will come up like System cannot find the file specified :
result = subprocess.run('ffmpeg -i output.mp4 -b 800k output.mp4')
File "C:\Program Files\Python37\lib\subprocess.py", line 488, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Program Files\Python37\lib\subprocess.py", line 800, in __init__
restore_signals, start_new_session)
File "C:\Program Files\Python37\lib\subprocess.py", line 1207, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
Question: How to fix code for correct compressing of videos?

Nearly correct! It looks like the only module you need is subprocess. You should run your command in run() function. Try this:
import subprocess
result = subprocess.run('ffmpeg -i output.mp4 -b 800k output.mp4')
print(result)

Related

python script in cron not reading a CSV unless it creates the CSV itself

I have the following script. It works when I run it in command line, and it works when I run it in cron.
The variable 'apath' is the absolute path of the file.
cat=['a','a','a','a','a','b','b','b','b','b']
val=[1,2,3,4,5,6,7,8,9,10]
columns=['cat','val']
data=[cat,val]
dict={key:value for key,value in zip(columns,data)}
statedata_raw=pd.DataFrame(data=dict)
statedata_raw.to_csv(apath+'state_data.csv',index=False)
statedata_raw2=pd.read_csv(apath+'state_data.csv')
statedata_raw2.to_csv(apath+'state_data2.csv',index=False)
But when I try to run the first part manually, creating the first csv, and then run the second part through cron, the second read_csv statement fails. I checked the permissions on the state_data.csv file and they are fine. It's set to -rwxr-xr-x
To be specific: I first run this script manually through command line. It executes and creates state_data.csv. Then I check the permissions of state_csv, and they are -rwxr-xr-x
cat=['a','a','a','a','a','b','b','b','b','b']
val=[1,2,3,4,5,6,7,8,9,10]
columns=['cat','val']
data=[cat,val]
dict={key:value for key,value in zip(columns,data)}
statedata_raw=pd.DataFrame(data=dict)
statedata_raw.to_csv(apath+'state_data.csv',index=False)
and then this script via cron, which fails, and gives the error message below
statedata_raw2=pd.read_csv(apath+'state_data.csv')
statedata_raw2.to_csv(apath+'state_data2.csv',index=False)
This is the error that I get from the system
Traceback (most recent call last):
File "/users/michaelmader/wdtest.py", line 39, in <module>
statedata_raw2=pd.read_csv(apath+'state_data.csv')
File "/opt/miniconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 676, in parser_f
return _read(filepath_or_buffer, kwds)
File "/opt/miniconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 448, in _read
parser = TextFileReader(fp_or_buf, **kwds)
File "/opt/miniconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 880, in __init__
self._make_engine(self.engine)
File "/opt/miniconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1114, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "/opt/miniconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1891, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas/_libs/parsers.pyx", line 374, in pandas._libs.parsers.TextReader.__cinit__
File "pandas/_libs/parsers.pyx", line 678, in pandas._libs.parsers.TextReader._setup_parser_source
OSError: Initializing from file failed
To summarize
Run complete script through Terminal: state_data2.csv is created: pass
Run complete script through cron: state_data2.csv is created: pass
Run first part through Terminal, second part through cron: fail
I am on MacOS and I already gave crontab full disk access in system preferences.
I figured out the problem. The issue was the permissions that were granted to cron in MacOS. I thought I had solved it by giving \usr\bin\crontab full disk access, but I actually needed to give full disk access to usr\sbin\cron
The steps for doing this can be found here: https://blog.bejarano.io/fixing-cron-jobs-in-mojave/.
Once I made that change everything worked fine.

Converting .TIF to .PDF gives PIL: Error reading image

I've been trying to batch process some .TIF files and convert them to PDFs. I did have it working, but then after trying to change img2pdf so it would accept larger files I was never able to get the same program running again, even after re-installing.
Currently this is throwing out the following error:
>>>>
ImageOpenError: cannot read input image (not jpeg2000). PIL: error reading image: cannot identify image file <_io.BytesIO object at 0x000001A608255EB8>
Here is the code I've been using. Anyone got any suggestions? Thanks in advance.
import img2pdf, sys, os, time
image_directory = r"PATH"
image_files = []
for root, dirs, files in os.walk(image_directory):
for file in files:
if file.endswith(".tif") or file.endswith(".TIF"):
print("Discovered this TIF: ", os.path.join(root, file))
image_files.append(os.path.join(root, file))
for image in image_files:
output_file = image[:-4] + ".pdf"
print ("Putting all TIFs into ", output_file)
pdf_bytes = img2pdf.convert(image)
file = open(output_file,"wb")
file.write(pdf_bytes)
Here is the full traceback
Traceback (most recent call last):
File "<ipython-input-37-fe96d5eeb049>", line 1, in <module>
runfile('PATH', wdir='PATH')
File "PATH", line 704, in runfile
execfile(filename, namespace)
File "PATH", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "PATH", line 23, in <module>
pdf_bytes = img2pdf.convert(image_files)
File "PATH", line 1829, in convert
) in read_images(rawdata, kwargs["colorspace"], kwargs["first_frame_only"]):
File "PATH", line 1171, in read_images
"PIL: error reading image: %s" % e
ImageOpenError: cannot read input image (not jpeg2000). PIL: error reading image: cannot identify image file <_io.BytesIO object at 0x000001A6082BE3B8>
If, as I understand it, you want to recursively find all TIFF images and convert each one to a correspondingly named PDF file, you can do that simply and in parallel with GNU Parallel and ImageMagick like this in Terminal:
find . -iname "*tif" -print0 | parallel -0 --dry-run mogrify {} {.}.pdf
Sample Output
mogrify ./OpenCVTIFF64/result.tif ./OpenCVTIFF64/result.pdf
mogrify ./OpenCVTIFF64/a.tif ./OpenCVTIFF64/a.pdf
mogrify ./OpenCVBasics/a.tif ./OpenCVBasics/a.pdf
mogrify ./CImgDump/image.tif ./CImgDump/image.pdf
That command says... "Starting in the current directory, recursively find all TIFF files, whether upper or lowercase or some mixture and pass their names, null-terminated, to GNU Parallel. It should then read each name and run ImageMagick mogrify to convert that TIFF into a file with same name but the extension replaced with PDF."
If it does what you want, remove the --dry-run and do it again for real.
So this ended up working once I executed pip install 'Pillow>=6.0.0' --force-reinstall, even though the command itself didn't execute properly. I get a few warnings when I run, but it's now working. Short version is, it was an issue with Pillow.

what should i do for playing a m4a file in python3?

I used pygame and mplayer library to play a m4a music file in python languages,but all failed. Is there a library i can use to play m4a file in python?
here is my code:
pipes = dict(stdin=PIPE, stdout=PIPE, stderr=PIPE)
mplayer = Popen(["mplayer", r"C:\Users\sam\PycharmProjects\untitled\music.m4a"], **pipes)
# to control u can use Popen.communicate
mplayer.communicate(input=b">")
sys.stdout.flush()
i used the pycharm ,and the result is :
Traceback (most recent call last):
File "C:/Users/sam/PycharmProjects/untitled/tt.py", line 23, in
mplayer = Popen(["mplayer", r"C:\Users\sam\PycharmProjects\untitled\music.m4a"], **pipes)
File "C:\Users\sam\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 707, in init
restore_signals, start_new_session)
File "C:\Users\sam\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 990, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
Here is a link to a good thread that I believe answers the exact same thing that you are having issues with.
Play m4a in python script with mplayer

FileNot FoundError:fluidsynth

I just want to convert my midi files to mp3 by using midi2audio, i use this code:
----------
from midi2audio import FluidSynth
FluidSynth().midi_to_audio('test.mid','test.mp3')
---------- or
from midi2audio import FluidSynth
FluidSynth().play_midi('test.mid')
but i got the same result:
----------
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/blake/Desktop/Bsmart_music/test/t_p/1.py
Traceback (most recent call last):
File "/Users/blake/Desktop/Bsmart_music/test/t_p/1.py", line 5, in <module>
FluidSynth().play_midi('test.mid')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/midi2audio.py", line 49, in play_midi
subprocess.call(['fluidsynth', '-i', self.sound_font, midi_file, '-r', str(self.sample_rate)])
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 267, in call
with Popen(*popenargs, **kwargs) as p:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'fluidsynth': 'fluidsynth'
Process finished with exit code 1
----------
So, i try to copy the fold "fluidsynth" to "midi2audio", but it still doesn't work. I have installed both midi2audio and fluidsynth, who knows what happened?
you must copy "fluidsynth" in some folder pointed by your PATH environ variable
( type "echo $PATH" in terminal app to see what is registered actually ).
On unix-like systems python will usually find fluidsynth located at /usr/bin/fluidsynth ( as /usr/bin is listed in the PATH ). on Os X things are not much different any documentation should fit. A common practice is to use /usr/local/bin folder for adding custom programs.
Maybe you should install fluidsynth first
for ubuntu:
sudo apt-get install fluidsynth

Subprocess library won't execute compgen

I am trying to make list of every command available on my linux (Lubuntu) machine. I would like to further work with that list in Python. Normally to list the commands in the console I would write "compgen -c" and it would print the results to stdout.
I would like to execute that command using Python subprocess library but it gives me an error and I don't know why.
Here is the code:
#!/usr/bin/python
import subprocess
#get list of available linux commands
l_commands = subprocess.Popen(['compgen', '-c'])
print l_commands
Here is the error I'm getting:
Traceback (most recent call last):
File "commands.py", line 6, in <module>
l_commands = subprocess.Popen(['compgen', '-c'])
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
I'm stuck. Could you guys help me with this? How to I execute the compgen command using subprocess?
compgen is a builtin bash command, run it in the shell:
from subprocess import check_output
output = check_output('compgen -c', shell=True, executable='/bin/bash')
commands = output.splitlines()
You could also write it as:
output = check_output(['/bin/bash', '-c', 'compgen -c'])
But it puts the essential part (compgen) last, so I prefer the first variant.
I'm not sure what compgen is, but that path needs to be absolute. When I use subprocess, I spell out the exact page /absolute/path/to/compgen

Resources