how to run an executable with python json - python

so I have this executable binary file that can be run via terminal
and by python
using code
$`python3 shell_c.py`
where python file contains
import subprocess
def executable_shell():
x=subprocess.run('cd build && ./COSMO/methane_c0.outmol.cosmo', shell=True, capture_output=True)
print(x)
executable_shell()
where COSMO is my executable name and "methane_c0.outmol" is the dynamic value that should be changed along with ".cosmo" which is an extension)
so to get these values from the JSON file I have created a JSON file
with input
{
"root_directory": "C:\\Users\\15182\\cosmo theory\\COSMO\\UDbase8",
"file_name": "methane_c0",
"file_format": ".cosmo",
"output1": "N_atoms",
"output2": "total number of segments"
}
now all that is left is to pass the value of file_name and file_format to the subprocess code to run it.
but I am not getting how to do go about it.
code I have written so far is basic
import json
with open ("parameters.json") as file:
data =json.load(file)
print(type(data))
pront(data)
how should I go so that values can be passed to a python file?

Something like this?
import json
import subprocess
with open ("parameters.json") as file:
data =json.load(file)
dynamic_file_name = data['file_name']+'.outmol'+data['file_format']
def executable_shell():
x=subprocess.run('cd build && ./COSMO/'+dynamic_file_name, shell=True, capture_output=True)
print(x)
executable_shell()

Related

Running one python script from another script with command line argument having executable in it

I am trying to run a python script within another python script. Which will run 10 times and produce 10 outputs.
I want to run program1.py inside program2.py. Now my program1.py was initially taking a C executable inside it and it takes 1 command line argument.
The program1.py looks like below:
import os
import sys
dataset = sys.argv[1]
os.system(f"/home/Dev/c4.5 -u -f {dataset}")
os.system(f"/home/Dev/c4.5rules -u -f {dataset}")
os.system(f"/home/Dev/c4.5rules -u -f {dataset} > Temp")
f = open('Temp')
# Some code
Where c4.5 and c4.5rules are the name of the executable files. To run this I was using python3 program1.py dataset_name
Now I am trying to put this program1.py inside program2.py and I am trying this below approach:
import os
import subprocess
# Some code
for track in range(0, 10):
with open(f'Train_{track}', 'r') as firstfile, open(f'DF_{track}.data', 'w') as secondfile:
for line in firstfile:
secondfile.write(line)
os.system("/home/Dev/program1.py DF_track")
#subprocess.Popen("/home/Dev/program1.py DF_track", shell=True)
Where I simply want to get the output of program1.py 10 times and want to use DF_track as the command line input for each output generation.
Using above approach I am getting lots of error. Please help.
Edit_1 :
Actually whenever I am trying to run, my cursor is not working, it is freezing, so unable to copy the errors.
Here are some of them :
1. attempt to perform an operation not allowed by security policy.
2. syntax error : word expected (expecting ")")
Imagine I have 2 files, the first file is a.py and the other is b.py and I want to call the a.py from b.py.
The content of a.py is:
print('this is the a.py file')
and the content of b.py is:
import os
stream = os.popen('python3 a.py')
output = stream.read()
print(output)
Now when I call b.py from terminal I get the output I expect which is a.py print statment
user#mos ~ % python3 b.py
this is the a.py file
You can do this with subprocess too instead of os module.
Here is a nice blog I found online where I got the code from: https://janakiev.com/blog/python-shell-commands/
See the example below.
a.py
def do_something():
pass
b.py
from a import do_something
do_something()

Curl command in Python 3

I want to execute a curl with command in python.
Usually, I just need enter the command in terminal and press return key.
The command shows below:
curl -H "`oauth2l header --json key.json mobileinsights`" https://mobileinsights.googleapis.com/v2/networks
The result is in json format.
Use the subprocess module to run your shell command.
import subprocess
result = subprocess.check_output('curl -H "`oauth2l header --json
key.json mobileinsights`" https://mobileinsights.googleapis.com/v2/networks', shell=True)
Then, use the json module to parse the JSON data returned by the server.
import json
result_json = json.loads(result)
You may load an OS and JSON load modules and then run
os.execute(curl URL) store it in any variable then convert it into JSON format with JSON load module

How to execute python script from another python script and send it's output in text file

I have a script test.py which is used for server automation task and have other script server.py which list out all server name.
server.py list all sevrer name in text.log file and this log file is used by test.py as a input.
I want one single script test.py to execute server.py from inside it and also redirect server.py script output to text.log file as well.
So far i have tried with execfile("server.py") >text.log in test.py which didn't worked.
Use subprocess.call with stdout argument:
import subprocess
import sys
with open('text.log', 'w') as f:
subprocess.call([sys.executable, 'server.py'], stdout=f)
# ADD stderr=subprocess.STDOUT if you want also catch standard error output

How to parse JSON passed on the command line

I am trying to pass JSON parameters through command line in Python:
automation.py {"cmd":"sel_media","value":"5X7_photo_paper.p}
how can I extract the values sel_media and 5X7_photo_paper.p?
I used the following code, but it is not working:
cmdargs = str(sys.argv[1])
print cmdargs
Provided you pass actual valid JSON to the command line and quote it correctly, you can parse the value with the json module.
You need to quote the value properly, otherwise your shell or console will interpret the value instead:
automation.py '{"cmd":"sel_media","value":"5X7_photo_paper.p"}'
should be enough for a bash shell.
In Python, decode with json.loads():
import sys
import json
cmdargs = json.loads(sys.argv[1])
print cmdargs['cmd'], cmdargs['value']
Demo:
$ cat demo.py
import sys
import json
cmdargs = json.loads(sys.argv[1])
print cmdargs['cmd'], cmdargs['value']
$ bin/python demo.py '{"cmd":"sel_media","value":"5X7_photo_paper.p"}'
sel_media 5X7_photo_paper.p
The above is generally correct, but I ran into issues with it when running on my own python script
python myscript.py '{"a":"1"}'
does not work directly in my terminal
so I did
python myscript.py '{\"a\":\"1\"}'

How can I convert a text file to audio (mp3) using ffmpeg on Ubuntu 11.04?

I would like to output .mp3 file from a text file on Ubuntu 11.04, using ffmpeg. Please, how do I do this? The best I could output is a .wav file. I intend to be able to use it in a Python file.
My output method for .wav is espeak -s 155 -a 200 -f details.txt -w details.wav
Well, I've found a way around it. I wrapped it in a Python script, as shown below:
from subprocess import Popen
from os import remove
def tts(text_file, wav_file, mp3_file):
Popen(["espeak", "-v", "en-uk", "-f", text_file, "-w", wav_file]).communicate()
Popen(["lame", "--ta", "nwaomachux", "--tt", "Latest Update", wav_file, mp3_file]).communicate()
remove(wav_file)
remove(text_file)
if __name__ == '__main__':
wav_ = '/home/nwaomachux/Dropbox/news_update.wav'
mp3_ = '/home/nwaomachux/Dropbox/news_update.mp3'
txt_ = '/home/nwaomachux/Dropbox/news_upd.txt'
tts(txt_, wav_, mp3_)
Please I'm open to suggestions and corrections. What I was able to achieve here is to output to .mp3 format without having to go through the ffmpeg I earlier wanted.

Categories

Resources