# sys.argv练习
# 写一个python脚本,在cmd里执行
# python xxx.py 用户名 密码 cp 文件路径 目的地址
# python xxx.py alex sb cp D:python_22day221.内容回顾.py D:python_22day21
# python xxx.py alex sb rm D:python_22day22
# python xxx.py alex sb rename D:python_22day22 D:python_22day23
import os
import sys
import shutil
if len(sys.argv) >= 5:
if sys.argv[1] =='alex' and sys.argv[2] == 'sb':
if sys.argv[3] == 'cp' and len(sys.argv) == 6:
if os.path.exists(sys.argv[4]) and os.path.exists(sys.argv[5]):
filename = os.path.basename(sys.argv[4])
path = os.path.join(sys.argv[5],filename)
shutil.copy2(sys.argv[4],path)
elif sys.argv[3] == 'rm' and len(sys.argv) == 5:
if os.path.exists(sys.argv[4]):
if os.path.isfile(sys.argv[4]):
os.remove(sys.argv[4])
else:
shutil.rmtree(sys.argv[4])
elif sys.argv[3] == 'rename'and len(sys.argv) == 6:
if os.path.exists(sys.argv[4]):
os.rename(sys.argv[4],sys.argv[5])
else:
print('您输入的命令无效')
将脚本改写成下面的样子:
import os
import sys
import getopt
import shutil
class Fileoperation(object):
def __init__(self,username,psw,func_name,path1='',path2=''):
self.username=username
self.psw=psw
self.func_name=func_name
self.path1=path1
self.path2=path2
def cp(self):
if os.path.exists(self.path1) and os.path.exists(self.path2):
filename = os.path.basename(self.path1)
target_path = os.path.join(self.path2,filename)
shutil.copy2(self.path1,target_path)
else:
print('path1或path2不存在')
def rm(self):
if os.path.exists(self.path1):
if os.path.isfile(self.path1):
os.remove(self.path1)
else:
shutil.rmtree(self.path1)
else:
print('path1目录不存在')
def rename(self):
if os.path.exists(self.path1):
os.rename(self.path1,self.path2)
def main(self):
if self.func_name == "cp":
Fileoperation.cp(self)
elif self.func_name == "rm":
Fileoperation.rm(self)
elif self.func_name == "rename":
Fileoperation.rename(self)
else:
print('func_name有误')
if __name__ == '__main__':
username=''
psw=''
func_name =''
path1=''
path2=''
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "h", ["username=","psw=","func_name=", "path1=", "path2="])
except getopt.GetoptError:
print('有错误发生','collin_file_operation.py --username username --psw psw --path1 source path --path2 target path')
sys.exit(2)
for opt, arg in opts:
if opt == "-h": # 提示,帮助功能
print('collin_file_operation.py --username username --psw psw --path1 source path --path2 target path')
sys.exit()
elif opt == "--username":
username = arg
elif opt == "--psw":
psw = arg
elif opt == "--func_name":
func_name = arg
elif opt == "--path1":
path1 = arg
elif opt == "--path2":
path2 = arg
# print(process_name + "--"+log_path+"--"+excel_path+"--"+new_excel_path+"")
handle = Fileoperation(username,psw,func_name,path1,path2)
handle.main()
cmd 执行的命令:
复制文件:
C:Users12078PycharmProjectsOldBoyDay22>
python collin_file_operation.py --username=alex --psw=123 --func_name=cp --path1=C:Users12078PycharmProjectsOldBoyDay22 est argethaha.py --path2=C:Users12078PycharmProjectsOldBoyDay22 est2
移除文件:
C:Users12078PycharmProjectsOldBoyDay22>
python collin_file_operation.py --username=alex --psw=123 --func_name=rm --path1=C:Users12078PycharmProjectsOldBoyDay22 est argethaha.py
重命名文件:
C:Users12078PycharmProjectsOldBoyDay22>
python collin_file_operation.py --username=alex --psw=123 --func_name=rename --path1=C:Users12078PycharmProjectsOldBoyDay22 est2 argethaha.py --path2=C:Users12078PycharmProjectsOldBoyDay22 est2 arget_hihi.py
之前写的uipath 调用 exe的例子:
import numpy as np
import pandas as pd
from pandas import DataFrame,Series
import sys,getopt # 用来解析参数的两个库
class HandleData():
def __init__(self,process_name,log_path='',excel_path='',new_excel_path=''):
self.process_name=process_name
self.log_path=log_path
self.excel_path=excel_path
self.new_excel_path=new_excel_path
def deal_with_data(self):
file_obj=open(self.excel_path)
df=pd.read_csv(file_obj)
# df=pd.read_csv(self.excel_path)
df=df.reindex(columns=['CNUM','COMPANY','C_col','D_col','E_col','F_col','G_col','H_col'],fill_value=None)
df.rename(columns={'COMPANY':'Company_New'}, inplace = True)
df=df.dropna(axis=0,how='all')
df['CNUM'] = df['CNUM'].astype('int32')
df = df.drop_duplicates(subset=['CNUM', 'Company_New'], keep='first')
df.to_csv(self.new_excel_path,index=False,encoding='GBK')
file_obj.close()
def writeLog(self):
with open(self.log_path,"a") as logfile:
logfile.write("
that's a test log message")
def writeEventLog(self):
with open(r"C:Users12078DesktopUIPATH_test 419EventLogs_Bot1.txt","a") as logfile:
logfile.write("
no function found" + self.process_name)
def mainprocess(self):
if self.process_name=="deal_with_data":
HandleData.deal_with_data(self)
elif self.process_name=="writeLog":
HandleData.writeLog(self)
else:
HandleData.writeEventLog(self)
if __name__ == "__main__":
process_name=""
log_path = ""
excel_path = ""
new_excel_path = ""
argv=sys.argv[1:]
try:
opts,args = getopt.getopt(argv,"h",["process_name=","log_path=","excel_path=","new_excel_path="])
except getopt.GetoptError:
print('cnum_company_data0418.py --process_name processname str --log_path logpath str --excel_path datafilepath str --new_excel_path outputfilepath str')
sys.exit(2)
for opt, arg in opts:
if opt == "-h": # 提示,帮助功能
print('cnum_company_data0418.py --process_name processname str --log_path logpath str --excel_path datafilepath str --new_excel_path outputfilepath str')
sys.exit()
elif opt == "--process_name":
process_name = arg
elif opt == "--log_path":
log_path = arg
elif opt =="--excel_path":
excel_path = arg
elif opt =="--new_excel_path":
new_excel_path = arg
# print(process_name + "--"+log_path+"--"+excel_path+"--"+new_excel_path+"")
handle=HandleData(process_name,log_path,excel_path,new_excel_path)
handle.mainprocess()