How to use date command inside Popen? - python-3.x

I cannot use parameters when invoking date command inside Popen.
I am using Ubuntu 18.04.2 LTS, Python 3.6.7. I am trying to just print date by invokin date command from shell, unfortunately I got errors which says
Traceback (most recent call last):
File "./123.py", line 15, in <module>
print_date()
File "./123.py", line 9, in print_date
MyOut = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
File "/usr/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/usr/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: "date '+%S'": "date '+%S'"
Code:
#!/usr/bin/python3
import subprocess
import time
import os
cmd = "date '+%S'"
def print_date():
MyOut = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = MyOut.communicate()
print(stdout)
print(stderr)
os.system(cmd)
print_date()
Could anyone explain what went wrong, and why Python tries to find file "date '+%S'" ?
It works when we change cmd to cmd = "date", so what is correct way of passing '+%S' ?

The normal way to pass a command to Popen() is with a list. Try this:
cmd = ["date" '+%S']

Related

Python file can't be found - AudioSegment export

I'm using AudioSegment to create mp3 files in Python. It was working well but I recently change computer and now when I execute these lines :
from pydub import AudioSegment
sound = AudioSegment.from_wav("myfile.wav")
sound = sound.set_frame_rate(48000)
sound.export("myfile.mp3", format="mp3")
I have an error on the last line when exporting :
sound.export("myfile.mp3", format="mp3")
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Temp\ipykernel_29992\2926845828.py", line 1, in <cell line: 1>
sound.export("myfile.mp3", format="mp3")
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\pydub\audio_segment.py", line 963, in export
p = subprocess.Popen(conversion_command, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 109, in __init__
super(SubprocessPopen, self).__init__(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 947, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1416, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable
The line in french say the file can't be found. Any idea how to fix ? I've installed the pydub and ffmpeg modules on this new computer. The script works fine on my previous computer. I'm using spyder.

how to run a list of bash commands with subprocess

code example:
import subprocess
cmd_list = ["ls -la", "touch a.txt", "hostname"]
for _,i in enumerate(cmd_list):
x = subprocess.run(i)
print(x)
print(x.args)
print(x.returncode)
print(x.stdout)
print(x.stderr)
hostname works as expected but ls -la not
expected output:
output of ls -la, touch and hostname
error hitted:
File "linux_cmd.py", line 8, in <module>
x = subprocess.run(i)
File "/usr/lib64/python3.6/subprocess.py", line 423, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ls -la': 'ls -la'```
subprocess.run() expects the arguments as a list when you give more than one argument.
Change you cmd_list to a list of lists when you want to give multiple arguments:
cmd_list = [["ls", "-la"], ["touch", "a.txt"], "hostname"]
https://docs.python.org/3/library/subprocess.html#subprocess.run

Sometimes throws Bad file descriptor error, sometimes doesn't

The following piece of code was working fine for a year, of late it intermittently started failing with following error, wonder if any OS or hardware change is causing this
import subprocess
def bash_command(cmd):
process = subprocess.Popen(cmd, shell=True, executable="/bin/bash")
process.wait()
bash_command("bash myscript.sh")
The error message is:
Traceback (most recent call last): File
"/Users/ishandutta2007/Documents/Projects/p2/shell_way/all_in_one_refill.py",
line 68,
bash myscript.sh File "/Users/ishandutta2007/Documents/Projects/p2/shell_way/all_in_one_refill.py",
line 31, in bash_command
process = subprocess.Popen(cmd, shell=True, executable="/bin/bash") File
"/Users/ishandutta2007/.pyenv/versions/3.6.0/lib/python3.6/subprocess.py",
line 707, in __init__
restore_signals, start_new_session) File "/Users/ishandutta2007/.pyenv/versions/3.6.0/lib/python3.6/subprocess.py",
line 1326, in _execute_child
raise child_exception_type(errno_num, err_msg) OSError: [Errno 9] Bad file descriptor

Subprocess Popen couldn't find 'play'

Popen from subprocess couldn't find 'play' or 'aplay'.
My OS is Mac10.13.6, when I called Popen from subprocess.py and executed the flowing code
import platform
from subprocess import Popen
player = 'play' if platform.system() == 'Darwin' else 'aplay'
Popen([player, '-q', filename])
I received the following errors
File "/Users/lyuzhiliang/mycroft-precise/precise/util.py", line 78, in play_audio
Popen([player, '-q', filename])
File "/Users/lyuzhiliang/anaconda3/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/Users/lyuzhiliang/anaconda3/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: 'play': 'play'
Do I need to install some dependencies?
I am not entirely sure, I think it has to be afplay. Maybe try to give the full path and look for the binary yourself. (I think /usr/bin/afplay)

Python3 subprocess can't run command "la" or "ll"

completeProcess = subprocess.run("la")
This is my code to run commands via python, and it raise this error:
Traceback (most recent call last):
File "script_senior.py", line 171, in <module>
completeProcess = subprocess.run("la") # doesn't capture output
File "/usr/lib/python3.5/subprocess.py", line 693, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'la'
My OS is ubuntu, and when enter "la" in terminal, it will list files(include hidden files) in current working directory. and "ll" cmd will list file details. but I can't use them in python's subprocess api
How can I achieve this function? Is there any common api to run commands or just the python didn't recognize "la"
la is an alias for 'ls -A'. That comes as a default shell alias in systems like Ubuntu. If you wanna run it just use:
completeProcess = subprocess.run(["ls","-A"])
and if you are looking for the stdout you can use something like:
completeProcess = subprocess.run(["ls","-A"] , stdout=subprocess.PIPE)
print(completeProcess.stdout.decode())

Resources