Python 2.6 run time error - python-2.6

STEPCAFControl which is available in python2.6 but webgl module is not available. So I am trying to run this below program .
from __future__ import print_function
import sys
from OCC.STEPCAFControl import STEPCAFControl_Reader
from OCC.STEPControl import STEPControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Display.SimpleGui import init_display
#from OCC.Display.WebGl import threejs_renderer
step_reader = STEPControl_Reader()
status = step_reader.ReadFile('./models/screw.step')
if status == IFSelect_RetDone: # check status
failsonly = False
step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
ok = step_reader.TransferRoot(1)
_nbs = step_reader.NbShapes()
aResShape = step_reader.Shape(1)
print("Success")
else:
print("Error: can't read file.")
sys.exit(0)
display, start_display, add_menu, add_function_to_menu = init_display()
display.DisplayShape(aResShape, update=True)
start_display()
#my_renderer = threejs_renderer.ThreejsRenderer(background_color="#123345")
#my_renderer.DisplayShape(aResShape)
but getting this error.
How to solve this issue? Any suggestion?

Related

Redirect multiprocessing.Process output properly

I want to spawn a process and redirect its stdout/stderr.
With subprocess.Popen this example seems to work properly but not with multiprocessing.Process.
main script:
from multiprocessing import Process, set_start_method
import subprocess
import os
os.chdir(os.path.dirname(__file__))
def sub():
import sys
sys.stdout = None
sys.stderr = None
sys.__stdout__ = None
sys.__stderr__ = None
subprocess.run(["tasklist"])
print("Test") # is not printed. OK!
if __name__ == "__main__":
set_start_method("spawn")
## multiprocessing.Process: tasklist output IS printed on console and is not redirected via sys.stdout. Why?
p = Process(target=sub)
p.start()
p.join()
## subprocess.Popen: tasklist output is printed to the file
fh = open("out", "w")
p2 = subprocess.Popen("python popen.py",
stdout=fh)
fh.close()
Content of popen.py:
import subprocess
if __name__ == "__main__":
subprocess.run(["tasklist"])

Python Watchdog Custom Event Handler Not Firing Correctly

I'm using Python's watchdog module to listen for created events on a certain directory. Where I do some processing on newly created .csv files. When I test my code with nothing in the handler the watchdog fires correctly for all pasted/created files, but when I add my code/logic inside the handler it fires less than expected (52/60 files for example).
OS used: Windows 10, code is expected to work on a Windows server.
Python version: 3.7.3
Code:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import pandas as pd
import numpy as np
from error_handling import ErrorHandler
import os
from timeloop import Timeloop
from datetime import timedelta
import json
from fill_data import OnMyWatch2
class OnMyWatch:
# Set the directory on watch
watchDirectory = "."
def __init__(self):
self.observer1 = Observer()
def run(self):
self.observer1.schedule(Handler() , self.watchDirectory, recursive = True)
self.observer1.start()
try:
while True:
time.sleep(1)
except:
self.observer1.stop()
print("Observer Stopped")
self.observer1.join()
class Handler(FileSystemEventHandler):
#staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
try:
# Event is created, you can process it now
print("Watchdog received created event - % s." % event.src_path)
pathlower = str(event.src_path).lower()
if ".csv" in pathlower:
print("File is csv file")
# Once any code is added here the problem happens
# Example:
# df = pd.read_csv(event.src_path, names= ALL_INI.columnlistbundle.split("|"), sep="|", encoding='latin-1', engine='python')
# arraySelectedColumnsBundle = ALL_INI.selectedcolumnsbundle.split(",")
# bundle_df = df[np.array(arraySelectedColumnsBundle)]
else:
print("File is not csv file")
except Exception as e:
ErrorHandler(0, 'In Observer ', '-7', 'Exception ' + str(e), '', 1, '')
if __name__ == '__main__':
if os.path.isdir("."):
watch = OnMyWatch()
watch.run()

How to use python-telegram-bot repository to send message to telegram user request?

I programmed a telegram bot for downloading torrents with python-telegram-bot repository; however, my functions seem to work on the server side and the responses appear on my terminal/console where im running the py-script and transmissionBT server, but it does not send the response back to the user. below is my code:
def get_torrent(MAGNET):
import subprocess
get_it = subprocess.run(["transmission-remote", "-a", "-D", "-o", "--utp", MAGNET])
return "*success*"
def list_torrent(LISTED):
import subprocess
get_list = subprocess.run(["transmission-remote", LISTED])
return "*listed*"
def del_torrent(TORRENT_NO):
import subprocess
del_torrent = subprocess.run(["transmission-remote", "-t", TORRENT_NO, "-r"])
return "*deleted*"
def crepttit(bot, update, args):
import time
MAGNET = " ".join(args)
media_content = get_torrent(MAGNET)
time.sleep(1)
bot.send_meessage(chat_id=update.message.chat_id, text=media_content)
def crepttl(bot, update, args):
import time
LISTED = " ".join(args)
listed_torrent = list_torrent(LISTED)
time.sleep(1)
chat_id = update.message.chat_id
bot.send_message(chat_id=chat_id, text=torrent_list)
def crepttd(bot, update, args):
import time
TORRENT_NO = " ".join(args)
deleted_torrent = del_torrent(TORRENT_NO)
time.sleep(1)
bot.send_meessage(chat_id=update.message.chat_id, text=deleted_torrent)
from telegram.ext import Updater, CommandHandler
import subprocess
import time
import os
TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
start_handler = CommandHandler("creptt", crepttit, pass_args=True)
dispatcher.add_handler(start_handler)
start_handler2 = CommandHandler("crepttl", crepttl, pass_args=True)
dispatcher.add_handler(start_handler2)
start_handler3 = CommandHandler("crepttd", crepttd, pass_args=True)
dispatcher.add_handler(start_handler3)
updater.start_polling()
updater.idle()

cx_freeze tkinter application not working with multiprocessing in Windows

I created a basic Tkinter GUI that has one button that when you click on it, it is supposed to use multiprocessing in order to open up 5 Chrome instances of "https://www.google.com." When I compile the script using cx_freeze, I click on the new exe and the button does nothing. Here is the code:
main.py
from tkinter import *
from selenium import webdriver
import os, multiprocessing
import numpy as np
def func():
print("bot started")
home = "https://www.google.com"
chromeOptions = webdriver.ChromeOptions()
user_txt_path = []
user_txt_path.append('\\chromedriver.exe')
filename = os.path.dirname(sys.argv[0])
path_to_chromedriver = str(os.path.abspath(filename) + user_txt_path[0])
driver = webdriver.Chrome(chrome_options=chromeOptions, executable_path=path_to_chromedriver) #DRIVER DRIVER!
driver.get_cookies()
driver.get(home)
def callback():
num = 5
for n in np.arange(num):
p = multiprocessing.Process(target=func)
p.start()
master = Tk()
b = Button(master, text="OK", command=callback)
b.pack()
mainloop()
setup.py
from cx_Freeze import setup, Executable
import sys
import os
from pathlib import Path
user_txt_path = []
base = "Console"#"Win32GUI"
user_txt_path.append('chromedriver.exe')
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
buildOptions = {"include_files": [user_txt_path[0], 'tcl86t.dll', 'tk86t.dll'], "packages": ['encodings', "os"], "includes": ['numpy.core._methods', 'numpy.lib.format'], "excludes": []}
executables = [
Executable('main.py', base=base)
]
home_path = str(Path.home())
pathname = str(os.path.dirname(sys.argv[0]))
setup(name='numbers',
version = '1.0',
#description = 'test',
#shortcutName="TachySloth",
#shortcutDir="DesktopFolder",
options = dict(build_exe = buildOptions),
executables = executables
)
Note that you need all of the include_files in your parent directory with main.py.

python3 tkinter gui not reacting on execution

I'm using tkinter for my python3 GUI. The script I wrote, when executing in IDLE. But when I try to execute it without the GUI is not responding.
Here's the code:
#! python3
from tkinter import *
import tkinter as tk
class Program:
nameC = ""
master = ""
varC = ""
def callback(self):
self.nameC= filedialog.askopenfilename()
def __init__(self):
self.master = Tk()
self.varC = StringVar(self.master)
l1 = Label(text="Open file", relief=RIDGE,width=15)
l1.grid(row=0,column=0)
b1 = Button(text='Open', command=self.callback)
b1.grid(row=0,column=1)
program = Program()
mainloop()
So far I have a button and a label. If I click on the button, a filedialog is opened using the callback function
EDIT: fixed one error in the code
If it helps, I'm using windows
So after running the script in the console ( as mentioned not IDLE) I figured out that I would have to import filedialog:
#! python3
from tkinter import *
from tkinter import filedialog # this is what I needed
import tkinter as tk
class Program:
nameC = ""
master = ""
varC = ""
def callback(self):
self.nameC= filedialog.askopenfilename()
def __init__(self):
self.master = Tk()
self.varC = StringVar(self.master)
l1 = Label(text="Open file", relief=RIDGE,width=15)
l1.grid(row=0,column=0)
b1 = Button(text='Open', command=self.callback)
b1.grid(row=0,column=1)
program = Program()
mainloop()

Resources