Python教程(四)参数提取pymysql
Python(四)
本系列其他教程:
Python教程(二):函数、异常、模块&包、文件读取、常用模块
Python教程(三):类&对象、闭包、装饰器、类型注解
Python教程(三):类&对象、闭包、装饰器、类型注解、MRO
文章目录
- Python(四)
- 一、shell脚本调用python并传递参数
- 1.1 shell中调用python脚本
- 1.2 python中获取参数
- 方法一
- 方法二
- 1.3 综合实例
- 二、操作SQL
- 2.1 创建连接&获取游标
- 2.2 执行查询类SQL
- 2.3 执行非查询类SQL
一、shell脚本调用python并传递参数
1.1 shell中调用python脚本
r=`/home/Python-3.9/bin/python3.9 /disk3/dictauto_review_2.py -p "my_product" -c "12345" -m "user"`
echo ${r}
解释:
- my_product、12345、user都是shell脚本中定义的变量,也可以使用
-p ${product}
传递不定参数 -p ${product}
:将变量product
的值传递给参数-p
,在python中获取-p的值就能得到传递的参数- 此代码首先会执行python脚本,然后将执行的python脚本的输出赋值给变量r,然后打印python的输出(即r)
- 在 Shell 中,反引号用于将命令的输出作为字符串赋值给变量
- 只想执行 Python 脚本而无需捕获其输出,则可以省略反引号和要赋值的变量
1.2 python中获取参数
方法一
使用 sys.argv
,sys.argv
是一个列表,其中包含传递给 Python 脚本的命令行参数。要使用此方法,按照以下步骤操作:
- 在 Python 脚本 hello.py 中,导入
sys
模块:
import sys
- 访问
sys.argv
列表以获取参数:
# 获取第一个参数
first_arg = sys.argv[1]# 获取第二个参数
second_arg = sys.argv[2]
# 使用 python hello.py '参数1' '参数2' 即可传递参数
方法二
使用 argparse
模块,argparse
模块提供了一种更高级的方法来解析命令行参数。它允许定义参数的名称、类型、帮助信息等。要使用此方法,按照以下步骤操作:
- 在 Python 脚本中,导入
argparse
模块:
import argparse
- 创建一个
argparse.ArgumentParser
对象:
parser = argparse.ArgumentParser()
- 使用
add_argument()
方法定义参数:
parser.add_argument("-p", "--product", help="Product name")
parser.add_argument("-c", "--commit-id", help="Commit ID")
parser.add_argument("-m", "--email", help="Email address")
解释:
parser.add_argument()
是argparse
模块中用于定义命令行参数的方法。parser.add_argument("-p", "--product", help="Product name")
表示将传递过来的-p参数传递给product,并自动在 Python 脚本中定义一个名为product
的命令行参数(注意不是普通变量)。所以之后想要从python脚本中获取-p参数时不能使用-p,要使用product,详见下述。
- 使用
parse_args()
方法解析参数:
args = parser.parse_args()
- 访问参数值:
# 左边是python普通变量,右侧是命令行参数
product = args.product
commit_id = args.commit_id
email = args.email
例如,在上述的shell脚本示例中,可以使用以下代码获取传递的参数:
import argparseparser = argparse.ArgumentParser()
parser.add_argument("-p", "--product", help="Product name")
parser.add_argument("-c", "--commit-id", help="Commit ID")
parser.add_argument("-m", "--email", help="Email address")args = parser.parse_args()product = args.product
commit_id = args.commit_id
email = args.email
1.3 综合实例
Shell脚本:
script=${ScriptName}
port=${YourPhonePort}
ip=${YourPhoneIP}r=`/usr/local/bin/python3 runScript.py -s ${script} -i ${ip} -p ${YourPhonePort}`
echo ${r}
Python代码:
import subprocess
import argparse parser = argparse.ArgumentParser() # 添加命令行参数
parser.add_argument("-s", "--scriptName", help="Product name")
parser.add_argument("-i", "--phoneIP", help="Commit ID")
parser.add_argument("-p", "--phonePort", help="Email address") # 解析参数
args = parser.parse_args() # 赋值变量
scriptName = args.scriptName
phoneIP = args.phoneIP
phonePort = args.phonePort cmd_run = r'airtest run Android/' + scriptName + r' --device Android://127.0.0.1:5037/' + phoneIP + r':' + phonePort + ' --log' subprocess.call(cmd_run, shell=True)
-
subprocess.call
是 Python 的subprocess
模块中的一个函数,用于运行外部命令并等待命令执行完成。-
如果
shell=True
,则表示命令会通过shell执行。 -
重定向命令输出:
import subprocesswith open("output.txt", "w") as f:retcode = subprocess.call("ls -l", shell=True, stdout=f) print("Return code:", retcode) # 在这个例子中,subprocess.call 将 ls -l 命令的输出重定向到文件 output.txt 中
-
指定命令工作目录:
import subprocess# 指定users目录 retcode = subprocess.call("ls -l", shell=True, cwd="/users") print("Return code:", retcode) # 在这个例子中,subprocess.call 在 /users 目录下执行 ls -l 命令。
-
二、操作SQL
- 首先通过pip安装:pip install pymysql。
- 通过pymysql操作数据库的通用步骤:
- 创建数据库连接对象。
- 通过数据库连接对象获取游标。
- 通过游标的
execute()
方法执行sql语句。(execute方法的返回值是影响的行数) - 如果游标执行的是查询语句,则
execute()
之后会将数据保存在游标对象内部,然后游标对象调用fetch()
方法获取查询结果。- 如果使用同一个游标对象来执行多个查询(execute方法),则每次查询后游标之前的查询结果都会被覆盖,所以需要把每次查询的结果保存到变量中再执行下一次查询。
- 游标每次读取后(fetch方法),都会将指针移到下一行数据,只有重置游标位置才能重复读取已经被读取过的数据。
- 如果游标执行的是增删改对表数据有影响,则执行完
execute()
之后需要使用数据库连接对象执行commit()
方法提交事务。- 最好把执行SQL语句放到捕获异常中,如果发生了异常,通过数据库连接对象执行
rollback()
方法来回滚。
- 最好把执行SQL语句放到捕获异常中,如果发生了异常,通过数据库连接对象执行
- 执行完成之后需要关闭数据库连接对象和游标对象。
2.1 创建连接&获取游标
from pymysql import *# 创建连接对象
conn1 = Connection(host='test.com',port=3306,user='test',password='test',database='testTable'
)# 打印数据库信息
print(conn1.get_host_info()) # socket test.com:3306
print(conn1.get_server_info()) # 5.7.31# 获取游标对象,用来执行SQL
myCursor = conn1.cursor()# 通过游标执行SQL...# 使用完之后要关闭连接和游标
myCursor.close()
conn1.close()
2.2 执行查询类SQL
- 此时表中只有两行数据。
- 游标的
fetchone()
方法用来读取一行数据;fetchall()
方法提取当前游标位置→结尾的数据。
from pymysql import *# 创建连接对象,之后操作的都是该对象
conn1 = Connection(host='test.com',port=3306,user='test',password='test',database='testTable'charset='utf8mb4'
)# 获取游标对象,用来执行SQL,一定是通过游标来执行SQL
myCursor = conn1.cursor()try:myCursor.execute("select * from gqzTest")# 使用游标对象读取第一行数据result1 = myCursor.fetchone()# 再次调用读取下一行数据,此时已经把游标的所有数据都读完了result2 = myCursor.fetchone()# 读取空的游标result3 = myCursor.fetchall()print(result1) # (1, 'user3', 'user3@example.com')print(result2) # (6, 'Jay', 'user2@example.com')print(result3) # ()# 重新执行execute方法,会把游标的内容覆盖,数据又出现了myCursor.execute("select * from gqzTest")result4 = myCursor.fetchall()print(result4) # (1, 'user3', 'user3@example.com'), (6, 'Jay', 'user2@example.com')except Exception as e:print(e)
finally:# 使用完之后要关闭连接和游标myCursor.close()conn1.close()
补充:
cursor.rowcount # 获取游标中结果的行数
cursor.rownumber # 获取当前游标的位置,从0开始
cursor.fetchall() # 获取的是当前游标位置→结尾的所有数据
cursor.rownumber = 0 # 将游标位置置为0,就可以从头获取数据
2.3 执行非查询类SQL
from pymysql import *# 创建连接对象,之后操作的都是该对象
conn1 = Connection(host='test.com',port=3306,user='test',password='test',database='testTable'charset='utf8mb4'
)# 获取游标对象,一定是通过游标来执行SQL
myCursor = conn1.cursor()try:# 插入一条数据myCursor.execute("INSERT INTO gqzTest (username, email) VALUES ('user2', 'user2@example.com');")# 更新数据mySql = "UPDATE gqzTest SET username = %s WHERE email = %s"values = ('Jay', 'user2@example.com')myCursor.execute(mySql, values)# 执行事务conn1.commit()
except Exception as e:print(e)# 如果出错整个事务回滚conn1.rollback()
finally:# 使用完之后要关闭连接和游标myCursor.close()conn1.close()
-
如果想要让代码自动提交事务,在创建数据库连接对象时添加
autocommit=True
:conn1 = Connection(host='test.com',port=3306,user='test',password='test',database='testTable'charset='utf8mb4',autocommit=True # 无需手动提交事务 )