I'm working on a mac. I get a Permission denied exception when running code. How do I run one python file inside the main python file?
import os
import telebot
from telebot import types
# --------------------------\ project files /-------------------------#
from auth_data import token, txt
bot = telebot.TeleBot(token)
# first launch, start of work
#bot.message_handler(commands=['start', 'help'])
def welcome(message):
markup = types.InlineKeyboardMarkup(row_width=1)
parse = types.InlineKeyboardButton('📩Get messages📩', callback_data='parse')
markup.add(parse)
photo = open('menu.jpg', 'rb')
bot.send_photo(message.chat.id, photo, caption=txt, reply_markup=markup, parse_mode="HTML")
# menu
#bot.callback_query_handler(func=lambda call: True)
def callback(call):
if call.message:
if call.data == 'parse':
os.system('/Users/valiev/code/python/telegram_bot_parser/parser.py')
if __name__ == '__main__':
bot.infinity_polling(none_stop=True, interval=0)
You are not running the file, but opening it. Try changing
os.system('/Users/valiev/code/python/telegram_bot_parser/parser.py')
to
os.system('python3 /Users/valiev/code/python/telegram_bot_parser/parser.py')
Related
I'm trying to use textFSM to compile some Juniper "show" command outputs and get specific fields from them and finally printing collected info in one run.
This is my code:
import textfsm
import getpass
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
import os
def enable_netconf(remote_device):
junos_device = ConnectHandler(**remote_device)
command_2 = junos_device.send_command("show interfaces")
junos_device.disconnect()
def main():
print("Enter Device info to check:\n")
tuser = input("Enter username: ")
tpw = getpass.getpass()
with open("D:\Documents\sample3.csv", encoding='utf-8') as tf:
for line in tf:
my_ip = line.rstrip(os.linesep)
remote_device = {
'device_type': 'juniper',
'ip': my_ip,
'username': tuser,
'password': tpw,
}
enable_netconf(remote_device)
with open("D:\Documents\juniper_junos_show_interfaces.textsm", "r") as f:
template = textfsm.TextFSM(f)
result = template.ParseText(command_2)
print(result)
if __name__ == '__main__':
main()
I used Netmiko to connect to Juniper vMX device. I also download textFSM "show interfaces" temple from this link (https://github.com/networktocode/ntc-templates/blob/master/ntc_templates/templates/juniper_junos_show_interfaces.textfsm) and saved them in D:\Documents folder.
first of All I need to make the basic function of textFSM to work. in the above code I got the error saying that "command_2" variable has not been defined which as seen I defined it inside the "def enable_netconf(remote_device)".
Would you please help me on this as I'm a newbie in Python.
Thanks.
If you want to use a variable in a different def, you can use the global command. In this example, just put "global comman_2" just below def enable_netconf(remote_device):
def enable_netconf(remote_device):
global command_2
junos_device = ConnectHandler(**remote_device)
command_2 = junos_device.send_command("show interfaces")
junos_device.disconnect()
I have a python script that sends notifications, it works fine in my ide but when I use pyinstaller to create an EXE. the script doesn't seem to work and no notification is played. There is also no errors when opening the EXE, it's just that no notification is being played. Also, when im creating the exe with pyinstaller I make sure to use --hidden-import pyler.platforms.win.notification.
from plyer import notification
def notifyMe(title, message):
notification.notify(
title = title,
message = message,
app_name= "Remind",
app_icon = "clock.ico",
timeout = 25,
)
notifyMe("Test", "test")
This is the code.
You can use the toast notifier library instead of pyler
from win10toast import ToastNotifier
toast = ToastNotifier()
toast.show_toast("Title here", "Message here", duration=10)
If you want to use pyler only, then I'm pretty sure that the problem is with the app icon destination folder. Try changing it to a specific path.
Instead of app_icon = "clock.ico"
Write app_icon = "C:\Users\clock.ico"
If this doesn't work, you can also write app_icon = "C:\\Users\\clock.ico"
When you use Pyinstaller, the location of the python file will no longer be the same which will give an error if you don't specify the exact destination folder.
Hope this answer helps!
I have following code which is able to read Mail Items from outlook and download the attachment when python code is run using eclipse. however, when the same code is compiled to an exe using pyinstaller, it fails to read the mail items with error: ComObject Unknown
The following code reads email item in a folder and downloads excel attachment from mail with specific subject. then strips off the password from the downloaded xls file and saves it as xlsx file for further processing.
The code below runs fine when run in eclipse environment or when called using python.exe from command prompt. but fails to recognize email item when run using exe compiled by pyinstaller.
I am using Windows 10 and outlook 2016 over exchange server
what is it that i am missing here?
below is the code block:
import win32com.client as wc
from datetime import date
import os
import configparser
print('Reading Config file')
config=configparser.ConfigParser()
config.sections()
config.read('ReadOutlook.config')
configuration=config['DEFAULT']
mailboxname=configuration['mailboxname']
mailfolder_to_look_for=configuration['mailfolder_to_look_for']
downloadpath=configuration['downloadpath']
ULMISPath=configuration['ULMISPath']
CFMISPath=configuration['CFMISPath']
ulmis_password=configuration['ulmis_password']
cfmis_password=configuration['cfmis_password']
ulmisSubjectcontent=configuration['ulmisSubjectcontent']
cfmisSubjectcontent=configuration['cfmisSubjectcontent']
ulmisfilenamesearch=configuration['ulmisfilenamesearch']
cfmisfilenamesearch=configuration['cfmisfilenamesearch']
print (date.today())
outlook = wc.Dispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
root = namespace.Folders.Item(mailboxname)
print(root.Name)
#print(root.Name)
MyMails=root.Folders.Item(mailfolder_to_look_for)
def Remove_password_xlsx(filename, pw_str,newfilename):
print('opening Excel Application')
xcl = wc.Dispatch("Excel.Application")
print('opening file:' ,filename)
wb = xcl.Workbooks.Open(filename, False, False, None, pw_str)
xcl.DisplayAlerts = False
print('Removing password for',filename)
wb.SaveAs(filename, None,'','')
print('Now saving as xlsx',newfilename)
wb=xcl.Workbooks.Open(filename,False,False,None)
wb.SaveAs(newfilename, FileFormat=wc.constants.xlOpenXMLWorkbook,CreateBackup=False)
xcl.Quit()
for mailitem in range(len(MyMails.Items),0,-1):
print(MyMails.Items[mailitem].Subject)
try:
if(MyMails.Items[mailitem].ReceivedTime.date()==date.today()
and ((MyMails.Items[mailitem].Subject.find(ulmisSubjectcontent)!=-1
and MyMails.Items[mailitem].Subject.find('With Collection')!=-1)
or MyMails.Items[mailitem].Subject.find(cfmisSubjectcontent)!=-1)):
print(MyMails.Items[mailitem].Subject)
# if i.Attachments:
for f in MyMails.Items[mailitem].Attachments:
if f.FileName.find(ulmisfilenamesearch)!=-1:
f.SaveAsFile(downloadpath + '\\ULMIS.xls')
Remove_password_xlsx(downloadpath+'\\ULMIS.xls'
, ulmis_password,ULMISPath)
print('removing ULMIS.xls')
os.remove(downloadpath+'\\ULMIS.xls')
break
else:
if f.FileName.find(cfmisfilenamesearch)!=-1:
f.SaveAsFile(downloadpath + '\\CFMIS.xls')
Remove_password_xlsx(downloadpath +'\\CFMIS.xls'
, cfmis_password,CFMISPath)
print('removing CFMIS.xls')
os.remove(downloadpath+'\\CFMIS.xls')
break
except:
print('an error occurred')
pass
Printing the Mail Subject gives error as:
Traceback (most recent call last):
File "ReadOutlook.py", line 45, in module File >"win32com\client\dynamic.py", line 279, in getitem File >"win32com\client\util.py", line 37, in getitem File >"win32com\client\util.py", line 56, in __GetIndex IndexError: list index >out of range
IndexError: list index out of range
Failed to execute script 'ReadOutlook' due to unhandled exception!
from the comments reced above by DS_London, i have now changed my code as follows:
import win32com.client as wc
from datetime import date
import os
import configparser
# while creating exe on pyinstaller use "win32timezone" in hidden import section
print('Reading Config file')
config=configparser.ConfigParser()
config.sections()
config.read('ReadOutlook.config')
configuration=config['DEFAULT']
mailboxname=configuration['mailboxname']
mailfolder_to_look_for=configuration['mailfolder_to_look_for']
downloadpath=configuration['downloadpath']
ULMISPath=configuration['ULMISPath']
CFMISPath=configuration['CFMISPath']
ulmis_password=configuration['ulmis_password']
cfmis_password=configuration['cfmis_password']
ulmisSubjectcontent=configuration['ulmisSubjectcontent']
cfmisSubjectcontent=configuration['cfmisSubjectcontent']
ulmisfilenamesearch=configuration['ulmisfilenamesearch']
cfmisfilenamesearch=configuration['cfmisfilenamesearch']
print (date.today())
# outlook = wc.Dispatch("Outlook.Application")
outlook = wc.gencache.EnsureDispatch("Outlook.Application")
namespace = outlook.GetNamespace("MAPI")
root = namespace.Folders.Item(mailboxname)
print(root.Name)
#print(root.Name)
MyMails=root.Folders.Item(mailfolder_to_look_for)
def Remove_password_xlsx(filename, pw_str,newfilename):
print('opening Excel Application')
xcl=wc.gencache.EnsureDispatch("Excel.Application")
# xcl = wc.Dispatch("Excel.Application")
print('opening file:' ,filename)
wb = xcl.Workbooks.Open(filename, False, False, None, pw_str)
xcl.DisplayAlerts = False
print('Removing password for',filename)
wb.SaveAs(filename, None,'','')
print('Now saving as xlsx',newfilename)
wb=xcl.Workbooks.Open(filename,False,False,None)
wb.SaveAs(newfilename, FileFormat=wc.constants.xlOpenXMLWorkbook,CreateBackup=False)
xcl.Quit()
for mailitem in range(len(MyMails.Items),0,-1):
# print(MyMails.Items[mailitem].ReceivedTime.date())
try:
if(MyMails.Items[mailitem].ReceivedTime.date()==date.today()
and ((MyMails.Items[mailitem].Subject.find(ulmisSubjectcontent)!=-1
and MyMails.Items[mailitem].Subject.find('With Collection')!=-1)
or MyMails.Items[mailitem].Subject.find(cfmisSubjectcontent)!=-1)):
print(MyMails.Items[mailitem].Subject)
# if i.Attachments:
for f in MyMails.Items[mailitem].Attachments:
if f.FileName.find(ulmisfilenamesearch)!=-1:
f.SaveAsFile(downloadpath + '\\ULMIS.xls')
Remove_password_xlsx(downloadpath+'\\ULMIS.xls'
, ulmis_password,ULMISPath)
print('removing ULMIS.xls')
os.remove(downloadpath+'\\ULMIS.xls')
break
else:
if f.FileName.find(cfmisfilenamesearch)!=-1:
f.SaveAsFile(downloadpath + '\\CFMIS.xls')
Remove_password_xlsx(downloadpath +'\\CFMIS.xls'
, cfmis_password,CFMISPath)
print('removing CFMIS.xls')
os.remove(downloadpath+'\\CFMIS.xls')
break
except:
# print('an error occurred')
pass
after this, I was getting error of missing import for win32timezone, which I corrected by adding hidden_import parameter in pyInstaller while building the exe - followed this post for it:
ImportError: No module named win32timezone when i make a singleone exe from a python script with pyInstaller
Friends, I am making a discord script using python I have to run this script multiple times with different parameters, I am trying that with os, threading, multiprocessing. when I am trying with this library that works only for first data Then it stuck, My code is below, please advise me.
note:- I am login as a user.
CSV file demo
auth-token1,channel-id1-1,channelid1-2
auth-token2,channel-id2-1,channelid2-2
...
...
main.py
import os
import csv
from time import sleep
import threading
import multiprocessing
rows = []
with open('data.csv', 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
# extracting each data row one by one
for row in csvreader:
rows.append(row)
for _ in rows:
li = _[1:]
cmd = _[0]
for i in li:
cmd = cmd+" "+str(i)
print(f'python3 script.py {cmd}')
os.system(f'python3 script.py {cmd}')
sleep(10)
script.py
import time
import os
import sys
from time import sleep
import os
from discord import Permissions, message
import discord
import logging
import sys
argumentList = sys.argv
print(argumentList[1:])
TOKEN_AUTH = argumentList[1]
os.environ['TZ'] = 'Asia/Kolkata'
time.tzset()
logging.basicConfig(handlers=[logging.FileHandler(filename="./discord.txt",
encoding='utf-8', mode='a+')],
format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
datefmt="%F %A %T",
level=logging.INFO)
channel = None
client = discord.Client()
ids = argumentList[2:]
sleep_time = 121
message = "enter your message"
#client.event
async def on_ready():
global channel
while True:
for _ in ids:
try:
channel1 = client.get_channel(int(_))
await channel1.send(message)
logging.info('1')
print('sleeping')
sleep(sleep_time*60)
except:
client.run(TOKEN_AUTH, bot=False)
client.run(TOKEN_AUTH, bot=False)
It is against Discord TOS to use bot=False otherwise known as a self bot (user)
All I will say is d.py is asynchronous and parts of your code are synchronous which is blocking.
client.run() is also a blocking method which is why your main.py stops running after the first run. Everything you do, with discord bots, needs to be async and within the client loop.
I recommend you rethink exactly what you are trying to do and do something that is not breaking their Terms of Service.
The reason because you are using ( client.run ) , this method will block the lines after it .
if you want to send messages in any place in your code ,
check this solution ^_^ :
client.run("TOKEN") blocking issue (python & discord.py)
I am trying to use the anaconda prompt to run my python script. It runs smoothly on the first call but stops there. I tried on Spyder, it works but I would like it to work on anaconda prompt or command line. Any reason why?
from decompress import decompress
from reddit import reddit
from clean import clean
from wikipedia import wikipedia
def main():
dir_of_file = r"D:\Users\Jonathan\Desktop\Reddit Data\Demo\\"
print('0. Path: ' + dir_of_file)
reddit_repo = reddit()
wikipedia_repo = wikipedia()
pattern_filter = "*2007*&*2008*"
print('1. Creating data lake')
reddit_repo.download_files(pattern_filter,"https://files.pushshift.io/reddit/submissions/",dir_of_file,'s')
reddit_repo.download_files(pattern_filter,"https://files.pushshift.io/reddit/comments/",dir_of_file,'c')
if __name__ == "__main__":
main()
The RS Downloaded is this line of code being ran:
reddit_repo.download_files(pattern_filter,"https://files.pushshift.io/reddit/submissions/",dir_of_file,'s')
Update:
Added the class/function
class reddit:
def multithread_download_files_func(self,list_of_file):
filename = list_of_file[list_of_file.rfind("/")+1:]
path_to_save_filename = self.ptsf_download_files + filename
if not os.path.exists(path_to_save_filename):
data_content = None
try:
request = urllib.request.Request(list_of_file)
response = urllib.request.urlopen(request)
data_content = response.read()
except urllib.error.HTTPError:
print('HTTP Error')
except Exception as e:
print(e)
if data_content:
with open(path_to_save_filename, 'wb') as wf:
wf.write(data_content)
print(self.present_download_files + filename)
def download_files(self,filter_files_df,url_to_download_df,path_to_save_file_df,prefix):
#do some processing
matching_fnmatch_list.sort()
p = ThreadPool(200)
p.map(self.multithread_download_files_func, matching_fnmatch_list)
It was the download which was taking a lot of time. I have changed network and it worked as expected. So there is no issue with cmd or anaconda prompt