python - 将参数传递给 python exe
问题描述
我正在尝试使用以下代码创建一个 python 可执行文件。
import pandas as pd
import pyodbc as po
import os
#variables
server = 'DESKTOP-9B94UPJ'
database = 'DB1'
username = 'etluser'
password = 'password'
rawfile_directory='E:\\Projects\\Ebay\\ETLApp\\'
cnxn = po.connect('DRIVER={SQL
Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
df=pd.read_csv(rawfile_directory+"SPSS_Files\\"+filename,usecols=var_filteredCols)
cnxn = po.connect('DRIVER={SQL
Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
sql_stmt = "INSERT INTO "+var_table+" ("+var_DBCols+") values("+var_placeholder+")"
cursor = cnxn.cursor()
cursor.fast_executemany = True
cursor.executemany(sql_stmt, df.values.tolist())
# print(f'{len(df)} rows inserted to the {MY_TABLE} table')
cursor.commit()
cursor.close()
cnxn.close()
我使用 pyinstaller 创建了一个 exe
pyinstaller --onefile etl.py
我想将运行时上的数据库凭据和文件夹路径传递给 exe。任何专家都可以告诉我如何实现这一目标吗?提前致谢
解决方案
If you don't want to create a GUI program that uses a user interface to extract credentials, you are probably left with command-line manipulation. You can easily do the above by passing the arguments in and then extracting them using sys.argv
For example:
import sys
if len(sys.argv) < 6:
raise ValueError("Not enough commandline arguments! Please run with <executable> <server> <database> <username> <password> <folder_path>")
server = sys.argv[1]
database = sys.argv[2]
username = sys.argv[3]
password = sys.argv[4]
rawfile_directory= sys.argv[5]
Then you can run your executable from command prompt using something like
C:\> <EXEfilename> DESKTOP-9B Ebay_CX etluser password E:\Projects\Ebay\ETLApp
If you want a fancier, more polished commandline interface, consider using argparse
so you can give your end users more help on how to use the different arguments to your executable, e.g. with usage instructions, --options instead of args, --help support, etc.
You could also ask for user input during runtime, e.g. after running the executable with input()
but this is less standard
See also: after compiling python program, how to input arguments
推荐阅读
- xml - 如何在属性之后读取 XML 值
- javascript - 量角器测试中的条件:如果元素包含特定文本则执行操作
- swift - alamofire 中的时间间隔来观察 API 的变化
- excel - 如果另一列数据相等,则对列中的值求和
- python - Beautifulsoup 分页使用下一个按钮
- json - 从文件读取配置时,Invoke-Command 失败并显示 $env 变量失败
- wordpress - 如何最好地实例化多个克隆站点并维护它们?
- ruby - 有条件地重启服务
- database - 实体关系图字段组合唯一性表示
- php - 如果密码包含在要解析的字符串中,Password_verify() 给出 true