Not able to send input argument values using subprocess Python Windows 10 - python

I am running a main script on windows 10 that calls another script called audioplayer.py using the subprocess module in python.
I want to send some input arguments when calling the audioplayer.py. So I wrote the main script as follows:
The following is the main script:
from subprocess import call
call(["python", "C:/Users/Jeff/Documents/audioplayer.py", "hey.wav"])
The following is my audioplayer.py:
"""OpenAL playback example."""
import os, sys, time
from openal.audio import SoundSink, SoundSource
from openal.loaders import load_wav_file
if len (sys.argv) < 2:
print ("Usage: %s wavefile" % os.path.basename(sys.argv[0]))
print (" Using an example wav file...")
dirname = os.path.dirname(__file__)
fname = os.path.join(dirname, "default.wav")
else:
fname = sys.argv[1]
sink = SoundSink()
sink.activate()
source = SoundSource(position=[10, 0, 0])
source.looping = True
data = load_wav_file(fname)
source.queue(data)
sink.play(source)
source.position = [source.position[0], source.position[1], source.position[2]]
sink.update()
time.sleep(2)
print("playing at %r" % source.position)
But I keep getting the following error even though the file does exist in the same directory as audioplayer.py
FileNotFoundError: [Errno 2] No such file or directory: 'hey.wav'
If I remove the hey.wav in the main script, it runs fine. It just doesn't seem to take any arguments.

try this:
call(["python", "C:/Users/Jeff/Documents/audioplayer.py", "C:/Users/Jeff/Documents/hey.wav"])
When you run the last one, the dir is the same with the main.py instead of the audioplayer.py.

Related

How to fix the program won't show other results

I have the following problem
import os
import json
import wmi
from random import choice
import time
filename = "kill.json"
with open(filename) as file:
kill = json.load(file)
def taskKill(imageNames: list):
cmdPrefix = 'taskkill /F /IM '
for imageName in imageNames:
cmd = cmdPrefix + imageName
os.system(cmd)
while 1==1:
c=wmi.WMI()
def check_process_running(rty):
if(c.Win32_Process(name=rty)):
print("Process is running")
taskKill(kill)
return
else:
print("Process is not running")
StrA =choice(kill)
check_process_running(StrA)
In this code that detects if the program is open and closes it, no matter how I change it, it always says Process is not running.
The output of your script is depending on the line if(c.Win32_Process(name=rty)) - it seems the return of Win32_Process is always True.
Insert a print statement with the value of Win32_Process before this line
Have you tried to provide the argument as a String ("StrA" instead of StrA)?
To check all current running processes, use:
import os, wmi
c = wmi.WMI()
for process in c.Win32_Process(name="python.exe"):
print(process.ProcessId, process.Name)
print("current processId:", os.getpid())

Trying to update command line inputs

My command line input looks like this:
python rerun_edit.py examples/Testing/config.yaml examples/Testing/0.blend examples/Testing/output
And my program looks like this:
import subprocess
import sys
import os
import pathlib
# this sets the amount of scenes
amount_of_scenes = 2
# this sets the amount of runs, which are performed
amount_of_runs = 5
# set the folder in which the run.py is located
rerun_folder = os.path.abspath(os.path.dirname(__file__))
blend_path = ["examples/Testing/0.blend"]
for scene_id in range(amount_of_scenes):
# the first one is the rerun.py script, the last is the output
used_arguments = str(sys.argv[1]) + (blend_path) + str(sys.argv[-1])
output_location = os.path.abspath(sys.argv[-1])
for run_id in range(amount_of_runs):
# in each run, the arguments are reused
cmd = ["python", os.path.join(rerun_folder, "run.py")]
cmd.extend(used_arguments)
# the only exception is the output, which gets changed for each run, so that the examples are not overwritten
#cmd.append(os.path.join(output_location, str(run_id)))
cmd.append(output_location)
print(" ".join(cmd))
# execute one BlenderProc run
subprocess.call(" ".join(cmd), shell=True)
print(used_arguments)
print(cmd)
#get the blend file
old_blend_file = str(scene_id) + ".blend"
new_blend_file = str(scene_id + 1) + ".blend"
blend_path = pathlib.Path(str(blend_path).replace(old_blend_file, new_blend_file))
print(blend_path)
It reads the command line inputs and executes a run.py program for a certain amount of runs.
After the runs I need to update the command line input to the following:
python rerun_edit.py examples/Testing/config.yaml examples/Testing/1.blend examples/Testing/output
So that it executes again for a certain amount of runs but with a different .blend file as input.
I tried to implement a for loop and adjust the paths name after the runs completed but I always getting an error saying:
used_arguments = str(sys.argv[1]) + (blend_path) + str(sys.argv[-1])
TypeError: can only concatenate str (not "list") to str
Can anyone help me out? Any help is highly appreciated.
Thank you very much :)
Here it is
import subprocess
import sys
import os
import pathlib
# this sets the amount of scenes
amount_of_scenes = 2
# this sets the amount of runs, which are performed
amount_of_runs = 5
# set the folder in which the run.py is located
rerun_folder = os.path.abspath(os.path.dirname(__file__))
blend_path = "examples/Testing/0.blend"
for scene_id in range(amount_of_scenes):
# the first one is the rerun.py script, the last is the output
used_arguments = [sys.argv[1], blend_path, sys.argv[-1]]
output_location = os.path.abspath(sys.argv[-1])
for run_id in range(amount_of_runs):
# in each run, the arguments are reused
cmd = ["python", os.path.join(rerun_folder, "run.py")]
cmd += used_arguments
# the only exception is the output, which gets changed for each run, so that the examples are not overwritten
#cmd.append(os.path.join(output_location, str(run_id)))
cmd.append(output_location)
print(" ".join(cmd))
# execute one BlenderProc run
subprocess.call(" ".join(cmd), shell=True)
print(used_arguments)
print(cmd)
blend_path = pathlib.Path(blend_path.replace(("%d.blend" % scene_id), ("%d.blend" % (scene_id + 1))))
print(blend_path)
Please check if it works and comment me if there are any errors

How does if __name__ == '__main__': takes file path

I have written a driver code to take file path from user and use that file path in my functions. Driver code is as below;
import sys
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: %s input_file" % sys.argv[0])
sys.exit()
file_path = sys.argv[1]
connection, color, numOf_Nodes,links = read_problem(file_path)
print(links)
graph_coloring(connection, color, 0, numOf_Nodes)
But when I run this code I got following error:
Usage: C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py input_file
An exception has occurred, use %tb to see the full traceback.
SystemExit
Shouldn't it ask for a file path from user? I am new to use a driver code therefore I might skip to write some parts for the driver code to work.
Any help?
The code is expecting that the user pass a file path on the command line. You want to execute your code with something like this:
python ipykernel_launcher.py /path/to/input/file
Upon execution of your code, the variable file_path will get a value of /path/to/input/file.
The variable sys.argv contains the script name in the first position, followed by each of the arguments passed to the script on the command line. That's why 2 is the appropriate expectation here...the first value in the array is the script name. The second value is the file path argument to the program.

Calling a sub process after for loop is completed in python

I have python script like below. In this script, I am collecting stdout and stderr of the script in a file and storing in Linux.
In this script, I am running the function path_finder in a loop over input_file
In this script, I am using subprocess to move data in Linux to a different location.
I want this subprocess call to run after finishing the loop but instead, it runs when the loop runs for the first time and when the second time the loop runs it throws an error which is expected. As the file is present it throws an error.
#!/usr/bin/python
import os
import sys
import traceback
import subprocess
def path_finder(
table,
mysql_user,
user,
dir,
):
day = datetime.now().strftime('%Y-%m-%d')
month = datetime.now().strftime('%Y-%m')
Linux_path = '/data/logging/{}'.format(input_file)
New_path = '/user/{}/{}/logging/{}/{}/{}'.format(user,dir,mysql_user,month,day)
subprocess.call(["rm", Linux_path])
so = se = open('/data/logging/{}'.format(input_file), 'a',
0)
#re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
### CODE:
Do something
### if errors the print traceback
### repeat the same for every table in input file
## Execute below statement after for loop completed
subprocess.call(["cp", Linux_path, New_path])
if len(sys.argv) != 5:
print 'Invalid number of args......'
exit()
input_file = sys.argv[1]
mysql_user = sys.argv[2]
user = sys.argv[3]
dir = sys.argv[4]
input = open("{}.format(input_file)", "r")
for table in input:
path_finder(
table,
mysql_user,
user,
dir,
)
sc.stop()
print
How can I change my script so that the sub process call will run after the for loop is done?
I don't see what the problem is. The statement you want to execute last is currently present in the function 'path_finder' which is why it is running every time.
To make this run only once and after the for loop is finished, put the statement after it.
for table in input:
path_finder(
table,
mysql_user,
user,
dir,
)
subprocess.call(["cp", Linux_path, New_path])
This should do it.

Why is `subprocess.call` not invoking the command

I'm trying to run a .wav file through ffmpeg using the subprocess.call(shell=True) in the following code and it doesn't seem to run. I know this because the output_file isn't created and I'm getting an exception in the open() method.
What am I doing wrong?
try:
import pocketsphinx
except:
import pocketsphinx as ps
import sphinxbase
import subprocess
import os
hmmd = "../../Pocketsphinx_Files/en-us-8khz"
lmdir = "../../Pocketsphinx_Files/cmusphinx-5.0-en-us.lm"
dictp = "../../Pocketsphinx_Files/cmu07a.dic"
output_filename = "../../temp/ps_output.wav"
def recognize(filename="../../temp/temp_output.wav"):
command = "ffmpeg -i "+filename+" -ac 1 -ab 16 -ar 16000 "+output_filename
subprocess.call(command,shell=True)
wavFile = open(output_filename,"rb")
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
wavFile.seek(44)
speechRec.decode_raw(wavFile)
result = speechRec.get_hyp()
#os.remove(filename)
#os.remove(output_filename)
return result
if __name__=="__main__":
print(recognize())
edit: I've got ffmpeg installed.
Furthermore, when I run the subprocess.call() command from the python interpreter it seems to work. This is why I'm stumped.
I would recommend that you try using subprocess.check_call() or check_output instead of simply call. They will raise an exception if your program fails to execute correctly, instead of leaving you wondering why no output was generated.
I'm going to guess that you may somehow be having path issues with your executable in a Python environment
Try using this function with 'ffmpeg':
def is_exe(prog):
for path in os.environ["PATH"].split(os.pathsep):
if os.path.isfile(os.path.join(path, prog)):
if os.access(os.path.join(path, prog), os.X_OK):
return os.path.join(path, prog)
else:
print "Program '%s' found in '%s', but lacks executable permissions." % (prog, path)
return False
If it returns False, you're having problems with Python running ffmpeg, otherwise it's ffmpeg which is having problems making sense of your arguments.

Categories

Resources