I have two python script the first once contains my def callers and my command line arguments. The second one contains my defs that i want to use the command line arguments in. I was wondering if there was a way to call the command line arguments into the second script cause they do call some of the items that are needed in the second one from the comman line.

Recommended Answers

All 8 Replies

I would honestly just pass them as arguments. Nice and simple.

Your explanation is unclear. I don't think there is an issue. For example if the first file contains

args = parser.parse_args()

you can later call foo(args) and it doesn't matter if function foo() was defined in the first or the second script.

Is that the only way or is what im wanting to do even posisble

Is that the only way or is what im wanting to do even posisble

What you want to do is not at all clear.

ok thats what i was looking to do is call my args into my second script that way all i had to to on the command line is type test.py 1 2 3 and so that it can simplify my code that has teh defs in it .

If you could give an example with two short scripts first.py and second.py, it may help.

first py

import requests, shutil, datetime, os, csv, fnmatch, importconvert, StringIO, argparse


franchiseList = {}

with open('/home/hatterx/Desktop/Franchise_Name_Scrub_List.csv', 'r') as ff:
    fcf = csv.DictReader(ff)
    for frow in fcf:
        franchiseList[frow['Misc Franchise Name']] = frow
with open('/home/hatterx/Desktop/Franchise_Name_Scrub_List.csv', 'r') as fF:
    fcf = csv.DictReader(fF)
    for Frow in fcf:
        franchiseList[Frow['FRANCHISE Name - Directory']] = Frow

newrow={'Last Sale Date': '', 'Last Sale Amount': '', 'First Name': '', 'Last Name': '', 'Email': '', 'Franchise': '', 'State': '', 'Postal/Zip Code': '', 'Last Web Order ID': '', 'Date Added': '', 'Email Source':'', 'osg_web_dir': ''}
updaterow={'Last Sale Date': '', 'Last Sale Amount': '', 'First Name': '', 'Last Name': '', 'Email': '', 'Franchise': '', 'State': '', 'Postal/Zip Code': '', 'Last Web Order ID': '',  'osg_web_dir': ''}
new_field_names = newrow.keys()
update_field_names = updaterow.keys()
dt = datetime.datetime.now().strftime("%m_%d_%y_%H_%M_%S")
filebase = '/home/hatterx/Desktop'
filestart = filebase+'/Unprocessed/'
filedone = filebase+'/Processed/'
listTest = 'TEST List For API Integration'
listFACTS =  'FACTS Daily Import'
listOSG = 'OSG Special Offers Send Monthly'

importconvert.importToBronto
importconvert.convertToSor


parser = argparse.ArgumentParser(description='Convert SOR to FACTS update and OSG update.')
parser.add_argument('-b', help='The base path', required=False, dest='basePath', metavar='Base directory path',default='/home/hatterx/Desktop')
parser.add_argument('--se', help='Change sending emailaddress', required=False, dest='sendEmail', metavar='Sending Emailaddress', default='')
parser.add_argument('--re', help='Change reciveing emailaddress', required=False,dest='reviceEmail', metavar='Reciveing Emailaddress', default='')
parser.add_argument('--pw', help='Change password', required=False, dest='changePassword', metavar='Change Password', default='')
parser.add_argument('--tl', help='Change list to Test', required=False,dest='listTest', metavar='TEST List', default='TEST List For API Integration')
parser.add_argument('--fl', help='Change list to FACTS', required=False, dest='listFACTS', metavar='FACTS List', default='FACTS Daily Import')
parser.add_argument('--ol', help='Change list to OSG', required=False, dest='listOSG', metavar='OSG List', default='OSG Special Offers Send Monthly')
args = parser.parse_args()
print(args)

second py

import requests, shutil, datetime, glob, os, csv,fnmatch,StringIO,smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def convertToSor(fileName):

    snr=StringIO.StringIO()
    sur=StringIO.StringIO()

    cf2 = csv.DictWriter(snr, new_field_names)  
    cf4 = csv.DictWriter(sur, update_field_names)
    cf2.writeheader()
    cf4.writeheader()
    with open(fileName, 'r') as f1:
        cf1 = csv.DictReader(f1, fieldnames=('CustNo1', 'CustNo2', 'LastOrderDate', 'LastOrderAmount', 'FirstName', 'LastName', 'UserNo', 'EmailAddress', 'Franchise', 'PrevOrderDate', 'PrevOrderAmount', 'State', 'ZIP', 'Amt1', 'Amt2', 'Amt3', 'SalesPerson', 'WEBID'))

        cf3 = csv.DictReader(f1, fieldnames=('CustNo1', 'CustNo2', 'LastOrderDate', 'LastOrderAmount', 'FirstName', 'LastName', 'UserNo', 'EmailAddress', 'Franchise', 'PrevOrderDate', 'PrevOrderAmount', 'State', 'ZIP', 'Amt1', 'Amt2', 'Amt3', 'SalesPerson', 'WEBID'))



        for row in cf1:

            nr = newrow
            nr['Last Sale Date'] = row['LastOrderDate'].strip()
            nr['Last Sale Amount'] = row['LastOrderAmount'].strip()
            nr['First Name'] = row['FirstName'].strip()
            nr['Last Name'] = row['LastName'].strip()
            nr['Email'] = row['EmailAddress'].strip().split(',',1)[0]
            if nr['Email'] == '':
                continue

            fr_name = row['Franchise'].strip()
            if fr_name in franchiseList:
                nr['Franchise'] = franchiseList[fr_name]['FRANCHISE Name'].strip()
                if nr['Franchise'] == 'IGNORE':
                    continue
                nr['osg_web_dir'] = franchiseList[fr_name]['FRANCHISE Name - Directory'].strip()
                if nr['osg_web_dir'] == '':
                    nr['osg_web_dir'] = 'shop'
            else:
                nr['Franchise'] = 'SHOP'
                nr['osg_web_dir'] = 'shop'

            nr['State'] = row['State'].strip()
            nr['Postal/Zip Code'] = row['ZIP'].strip()
            nr['Last Web Order ID'] = row['WEBID'].strip()
            nr['Date Added'] = datetime.date.today().strftime('%m/%d/%Y')  
            nr['Email Source'] = 'FACTSauto'

            cf2.writerow(nr)

            ur = updaterow
            ur['Last Sale Date'] = row['LastOrderDate'].strip()
            ur['Last Sale Amount'] = row['LastOrderAmount'].strip()
            ur['First Name'] = row['FirstName'].strip()
            ur['Last Name'] = row['LastName'].strip()
            ur['Email'] = row['EmailAddress'].strip().split(',',1)[0]
            if ur['Email'] == '':
                        continue

            fr_name = row['Franchise'].strip()
            if fr_name in franchiseList:
                ur['Franchise'] = franchiseList[fr_name]['FRANCHISE Name'].strip()
                if ur['Franchise'] == 'IGNORE':
                    continueZoran,Preston

                ur['osg_web_dir'] = franchiseList[fr_name]['FRANCHISE Name - Directory'].strip()
                if ur['osg_web_dir'] == '':
                    ur['osg_web_dir'] = 'shop'
            else:
                ur['Franchise'] = 'SHOP'
                ur['osg_web_dir'] = 'shop'

            ur['State'] = row['State'].strip()
            ur['Postal/Zip Code'] = row['ZIP'].strip()
            ur['Last Web Order ID'] = row['WEBID'].strip()

            cf4.writerow(ur)

    return snr,sur

def importToBronto(mode, listName, filehandle):
    filehandle.seek(0)
    url = ''
    files = {'filename': (mode+'.csv', filehandle)}
    data = {'source': 'FACTS Daily Import', 'site_id': '', 'user_id': '', 'key': '', 'format': 'csv', 'action':mode, 'listname': listName, 'email': ''}
    res = requests.post(url, files=files, data=data)
    if res.status_code == requests.codes.ok:
        return True
    else:
        print res.status_code
        print res.text
        return False

franchiseList = {}

with open('/home/hatterx/Desktop/Franchise_Name_Scrub_List.csv', 'r') as ff:
    fcf = csv.DictReader(ff)
    for frow in fcf:
        franchiseList[frow['Misc Franchise Name']] = frow
with open('/home/hatterx/Desktop/Franchise_Name_Scrub_List.csv', 'r') as fF:
    fcf = csv.DictReader(fF)
    for Frow in fcf:
        franchiseList[Frow['FRANCHISE Name - Directory']] = Frow

newrow={'Last Sale Date': '', 'Last Sale Amount': '', 'First Name': '', 'Last Name': '', 'Email': '', 'Franchise': '', 'State': '', 'Postal/Zip Code': '', 'Last Web Order ID': '', 'Date Added': '', 'Email Source':'', 'osg_web_dir': ''}
updaterow={'Last Sale Date': '', 'Last Sale Amount': '', 'First Name': '', 'Last Name': '', 'Email': '', 'Franchise': '', 'State': '', 'Postal/Zip Code': '', 'Last Web Order ID': '',  'osg_web_dir': ''}
new_field_names = newrow.keys()
update_field_names = updaterow.keys()
dt = datetime.datetime.now().strftime("%m_%d_%y_%H_%M_%S")
DT = datetime.datetime.now().strftime("%Y_%M_%d")
filebase = '/home/hatterx/Desktop'
filestart = filebase+'/Unprocessed/'
filedone = filebase+'/Processed/'
listTest = 'TEST List For API Integration'
listFACTS =  'FACTS Daily Import'
listOSG = 'OSG Special Offers Send Monthly'




for File in os.listdir(filestart):
    if fnmatch.fnmatch(File, 'SOR935*'):
        snr,sur = convertToSor(filestart+File)
        cnt = sum(1 for line in open (filestart+File))
        res = importToBronto('add', listFACTS, snr)
        if True == res:

            print 'Sucsessful Add File Upload'

            res = importToBronto('update', listOSG, sur)
            if True == res:

                fromaddr="
                toaddr=""
                msg=MIMEMultipart()
                msg['From']=fromaddr
                msg['To']=toaddr
                msg['Subject']="FACTS nightly Bronto import processed "+str(cnt)+" records-"+DT
                body="There were "+str(cnt)+" records processed."
                msg.attach(MIMEText(body,'plain'))
                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login("", "")
                text = msg.as_string()
                server.sendmail(fromaddr, toaddr, text)
                print 'Sucsessful Update File Uploaded'         
                shutil.move(filestart+File, filedone+ dt +"_"+ File)
            else:
                print 'Failed to Import Update File'
        else:
            print 'Failed to Import Add File'

The second py is the one that im wanting to add the arguments from the first one

This is not a short example. I don't see where you need the args in the second script. I suggest another solution: write a third module, say handleargs.py

# handleargs.py

parser = argparse.ArgParser(...)
...
args = parser.parse_args()

then in first.py and second.py:

from handleargs import args
# now use args
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.