Instructions and command line operations in Python
P粉378890106
P粉378890106 2023-09-08 14:20:23
0
1
448

I'm writing a script in Python and I'm having some problems, I need to run a command with parameters taken from the database, I do this (mysql.connector needs to be 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. Am I correct to use os instead of subprocess?
  2. When I run this command, I get an answer in json format, how can I get the value from it? Do I need to include "import json"?
import json
 
# 一些JSON数据:
x = '{ "name":"John", "age":30, "city":"New York"}'
 
# 解析x:
y = json.loads(x)
 
# 结果是一个Python字典:
print(y["age"])

P粉378890106
P粉378890106

reply all(1)
P粉194541072

If you want to know why, you really should use subprocess, please read this.


In Python, the usage of import <module> is the same as the #include <module> preprocessing of C/C The instructions are very similar, although there are some differences. So you don't need to include import json, but instead import json.

Anyway, json is a Python built-in module for parsing, encoding, indenting and writing .json files, if you get a JSON formatted response, you really should consider decoding it into a Python dict object.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!