Python Script not executing

Hi Team,

I am trying to run the python script using UiPath.
I have used python scope and within that i have used Run Python script activity to run my script. I am using Python 3.6.0 version.

The execution starts and ends within seconds without any error. Also, nothing is happening as per my script.

I have a complex python code where i am fetching data from sales force and generation an excel.

Please help me to resolve this.

@shivani_bansal

Welcome to the UIpath Community.

Are you using 32 bit or 64 bit version of Python ?

Thank you !
I am using 32 bit version

1 Like

@shivani_bansal

Ok. Check below thread and see whether you followed all steps or not.

https://activities.uipath.com/docs/invoking-a-python-script

Yes!
And I am just using Run Python Script activity inside Python scope.
But nothing is happening.

@shivani_bansal

In the above thread, they provided example also and just download it and change python version and once run it. And check whether it is working fine or not.

Already did and its a simple addition subtraction python script so it will work fine.
But my script has a complex logic and advance features of python.

@shivani_bansal

Oh kk. First try to run that code in any python compiler and find where is the exact error.

Hi Shivani,

Please refer this link :

Get Back if you are stuck anywhere. Likewise you can also share your python script.

1 Like

Hi Rahul,

Thank you for the help. But this will not work for my script.
Below my script. Please have a look and help me what can be done.

Python Script

# -*- coding: utf-8 -*-
"""
Created on Wed May 22 15:09:11 2019

@author: Admin
"""

import numpy as np  
import pandas as pd
import re  
import nltk  
import pickle  
from nltk.corpus import stopwords 
from matplotlib import pyplot as plt
from sklearn.metrics import confusion_matrix,accuracy_score,roc_curve,auc
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from xgboost import XGBClassifier
#import scikitplot as skplt
from simple_salesforce import Salesforce
import logging
from datetime import datetime
import time
import json
import sys

start = time.time()

with open("pythonconfig - LoginIssue.json") as json_data_file:
    data = json.load(json_data_file)

logger=logging.getLogger(__name__)

if data["loggingLevel"]=="debug":
    logger.setLevel(logging.DEBUG)
elif data["loggingLevel"]=="info":
    logger.setLevel(logging.INFO)
elif data["loggingLevel"]=="warning":
    logger.setLevel(logging.WARNING)
elif data["loggingLevel"]=="error":
    logger.setLevel(logging.ERROR)
elif data["loggingLevel"]=="critical":
    logger.setLevel(logging.CRITICAL)

#log format
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

#create file handler
file_handler=logging.FileHandler("pythonCodeMyLearnLoginIssue{0}.txt".format(datetime.now().strftime("_%d-%B-%Y_%H-%M")))
stream_handler=logging.StreamHandler()

#add formatter to file_handler
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)

#add file_handler to logger
logger.addHandler(file_handler)
logger.addHandler(stream_handler)


try :
    chachedWords = stopwords.words('english')

   
    count_vect = pickle.load(open('count_vect.sav','rb'))
    tfidf_transformer = pickle.load(open('tfidf.sav', 'rb'))
    model = pickle.load(open('xgb_model.sav', 'rb'))

    #### Preprocessing steps ####
    TAG_RE = re.compile(r'<[^>]+>')

    def remove_tags(text):
        return TAG_RE.sub('', text)

    def remove_emails(text):
        pattern = re.compile(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+")
        return pattern.sub('',text)

    def clean_data(text):
        text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)
        text=text.replace("\n"," ")
        text=remove_tags(text)
        text=remove_emails(text)
        text=re.sub(r"\s+", " ", text)
        text=re.sub(r'[^\w\s]',"",text)
        text=re.sub(r'[0-9]+', '', text)
        text=text.replace("_","")
        return text.lower()

    porter_stemmer=nltk.PorterStemmer()
    def Tokenizer(str_input):
        words = re.sub(r"[^A-Za-z0-9\-]", " ", str_input).lower().split()
        words = [porter_stemmer.stem(word) for word in words if word not in chachedWords]
        return ' '.join([word for word in words if len(word) > 2])

  
    sf = Salesforce(username=data['salesforce']['username'], password=data['salesforce']['password'], security_token=data['salesforce']['security_token'])
    query="Select Id, CaseNumber, Subject, Description from Case where OwnerId='00G80000002JSwM' and Status='New'"
    df=pd.DataFrame(sf.bulk.Case.query(query))

    nrows, ncols = df.shape
    logger.info("No. of records from MyLearn Support Queue:{0}".format(nrows))

    if df.empty:
        raise exception("No Records!!")

    df['Subject']=df['Subject'].apply(lambda x: str(x).lower())
    df = df[~df.Subject.str.contains('out of the office|ooo|out of office|payment|remit',regex=True)]

    df['Description'] = df['Description'].apply(lambda x: str(x).lower())
    df = df[~df.Description.str.contains('out of the office|ooo|out of office|payment|remit', regex=True)]

    df.set_index('CaseNumber',inplace=True)

   
    df['Text'] = df['Description'].apply(str) + " " + df['Subject'].apply(str)
    df['Text'] = df['Text'].apply(lambda x: str(x).lower().replace('\n',' '))
    df['Clean_Text'] = df['Text'].apply(clean_data)
    X = df['Clean_Text']

    X = X.apply(Tokenizer)

  
    X_counts = count_vect.transform(X).toarray()
    features = tfidf_transformer.transform(X_counts).toarray()

    
    prob= model.predict_proba(features)[:,1]
    pred = [1 if i>0.55 else 0 for i in prob]

    df['Predicted Labels']=pred
    df['Login Issue Probability']=prob

    df.reset_index(inplace=True)



    final_df = df[df['Predicted Labels']==1][['CaseNumber','Subject', 'Description','Login Issue Probability']].copy(deep=True)
    final_df.to_excel('input_data.xlsx',index=False)

    nrows, ncols=final_df.shape
    logger.info("No. of Login Issue predicted records:{0}".format(nrows))

    ###########################
    logger.info("<<<INPUT FILE SUCCESSFULLY CREATED>>>")

except:
    logger.error("<<<Error>>>:\n {0}".format(sys.exc_info()))

finally:
    logger.info("*************************")
    logger.info("--- %s seconds ---" % (time.time() - start))


Hi @shivani_bansal
i have given the solution to exeuction of python script on the below link , it worked for most of the people . python script is so simple in the example but i have run the complex python script as well using that code.
Generally there is an issue with the script whenever we didn’t get any error at UiPath .Check your python script and the solution i have given .Meanwhile i will also check your python script.

Hi ,
im just learning python recently, those scripts i just want to run in ui path , can any one help me in this regarding which version need to install in ui path and activities can be invoke to run my python scripts

Hi Shivani,

Were you able to run this python code through Uipath. I have to do a NLP task through Uipath.

So my question is if we run code in which we have to import some libraries. Can uipath handle this??

yes import all the libraries before integrating with uipath

Do you have some sample code to share?

I’ve sample of integrating with uipath

Check this post