'Command in Python

I write script in Python and I have some problems, I need to run a command with a parameter that I get from the database, I did so (addition mysql.connector installed):

import mysql.connector
import os
 
mydb = mysql.connector.connect(
  host="localhost",
  user="name",
  password="pass",
  database="base"
)
 
mycursor = mydb.cursor()
 
mycursor.execute("SELECT * FROM `employee` LIMIT 2")
 
myresult = mycursor.fetchall()
 
for row in myresult:
    os.system('command ' + row[1])

I have 3 questions:

  1. is it correct that I use os and not subprocess?
  2. I get an answer in json format when I run this command, how do I get the value from there? Do I need to include "import json"?
import json
 
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
 
# parse x:
y = json.loads(x)
 
# the result is a Python dictionary:
print(y["age"])


Solution 1:[1]

is it correct that I use os and not subprocess?

You really should use subprocess, if you are asking why you should read this.


Do I need to include "import json"?

In Python import <module> has a very similar usage to C/C++ #include <module> preprocessor directive, even if it has some differences. So you don't include import json, but you import json.

Anyway json is a Python built-in module which parses, encodes, indents and writes to .json files, and if you get a JSON format response you really should consider it to decode this object to a Python dict.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1