Run Python script at command line - cannot find '__main__' module error - python-3.x

This is the first time I have ever tried running a python script from the command line. I type: python C:\Users\Jonathan\OneDrive - Mazars in Oman\Trading\Systems\FibMatrix\Testing Trade Analysis\Python Codes\CreateDataTablePythonScriptv2.py -a='USDJPY'
I get this error: C:\Users\Jonathan\AppData\Local\Programs\Python\Python39\python.exe: can't find '__main__' module in 'C:\\Users\\Jonathan\\OneDrive'
The script trying to run is:
import sqlite3
import sys
PairName = sys.argv[1]
DTBLocation = 'C:/Users/Jonathan/OneDrive - Mazars in Oman/Trading/Systems/FibMatrix/Testing Trade Analysis//SQLite/Trade Analysis.db'
connection = sqlite3.connect(DTBLocation)
cursor = connection.cursor()
TableName = PairName+'_DATA'
cursor.execute("""CREATE TABLE IF NOT EXISTS {}
(
Date_Time INTEGER,
Open REAL,
Max_60m_Box REAL
)""".format(TableName))
connection.commit()
connection.close()
I have searched, but was not able to find an answer. I appreciate the advice!

can't find '__main__' module in 'C:\\Users\\Jonathan\\OneDrive'
is the hint here
your path contains spaces (and it tried to be parsed up to first space)
try enclosing whole path with quotes
python "C:\Users\Jonathan\OneDrive - Mazars in Oman\Trading\Systems\FibMatrix\Testing Trade Analysis\Python Codes\CreateDataTablePythonScriptv2.py" -a='USDJPY'

Related

exec() not working when trying to execute a string containing the command "abs.__doc__"

I am trying to execute the command abs.__ doc__ inside the exec() function but for some reason it does not work.
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
exec(proper_string)
Essentially, I am going through a series of exercises and one of them asks to provide a short description of the entered function using the __ doc__ attribute. I am trying with abs.__ doc__ but my command line comes empty. When I run python in the command line and type in abs.__ doc__ without anything else it works, but for some reason when I try to input it as a string into the exec() command I can't get any output. Any help would be greatly appreciated. (I have deliberately added spaces in this description concerning the attribute I am trying to use because I get bold type without any of the underscores showing.)
As a note, I do not think I have imported any libraries that could interfere, but these are the libraries that I have imported so far:
import sys
import datetime
from math import pi
My Python version is Python 3.10.4. My operating system is Windows 10.
abs.__doc__ is a string. You should use eval instead of exec to get the string.
Example:
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
doc = eval(proper_string)
You can access it using globals():
def func():
"""Func"""
pass
mine = input("Please enter the name of a function: ")
print(globals()[mine].__doc__)
globals() return a dictionary that keeps track of all the module-level definitions. globals()[mine] is just trying to lookup for the name stored in mine; which is a function object if you assign mine to "func".
As for abs and int -- since these are builtins -- you can look it up directly using getattr(abs, "__doc__") or a more explicit: getattr(__builtins__, "abs").__doc__.
There are different ways to lookup for a python object corresponding to a given string; it's better not to use exec and eval unless really needed.

How to import psycopg2 into a new module im writing

So to simplify, I'm trying to write my own module (test.py) that looks as follows:
import psycopg2
get_data(xyz):
connection = psycopg2.connect(user="",
password="",
host="",
port="",
database="")
last_qry = """select * from xyz.abc"""
cursor = connection.cursor()
cursor.execute(last_qry)
last_data = cursor.fetchone()
cursor.close()
connection.close()
return last_data
in a different file I am running:
import test
get_data(xyz)
and I get the following error:
name 'psycopg2' is not defined
What am I doing wrong?
There are many bugs in these code snippets that you put here:
Your import should be like this:
from test import get_data
or in this way:
import test
test.get_data()
What is the use of xyz ? the second code snippet must return
NameError because xyz is not define;if you want to use it in last_qry you must have .format() for it.
What is the structure of directory that included the second file ?
and where is the first file?

sqlite3.OperationalError: unable to open database file - error occurs after a certain while

Tooling:
Raspberry Pi 3B
Raspbian
BME280
Python3
Flask
Sqlite3
Error code:
Traceback (most recent call last):
File "BME280_DataCollector.py", line 65, in <module>
File "BME280_DataCollector.py", line 45, in logData
sqlite3.OperationalError: unable to open database file
Working on Raspbian and want to store my sensor data in sqlite3 database.
Somehow following error code occurs:
"sqlite3.OperationalError: unable to open database file".
Firstly, I thought that I requested the database file too quickly and changed the the measurement time to minutes, but the error is still reproducible.
I looked into /tmp by df /tmp. But this file system is used by 12 % and not overloaded.
Also, I tried to give the full path and also the database all write and read permissions via chmod, but also no differents. In addition, I put the full path to the code.
Furthermore, I tried to make try and exception approaches which also weren't fruitful.
Nevertheless, I wanted to know if this failure occures at a certain number of interactions with the database. I found out that it always stopped at the 1020th interaction.
I also tried to restart the python script with a shell script but it didn't work out due to lack of experience and knowledge.
Code:
from flask import Flask,render_template,url_for,request,redirect, make_response, send_file
import random
import json
from time import sleep
from random import random
from flask import Flask, render_template, make_response
import datetime
import sqlite3
import sys
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
import os
import smbus2
import bme280
## FUNCTIONS ##
# get data
def getBMEdata():
port = 1
adress = 0x77
bus = smbus2.SMBus(port)
calibration_params = bme280.load_calibration_params(bus, adress)
bme_data = bme280.sample(bus, adress, calibration_params)
temp = '%.2f' % bme_data.temperature
hum = '%.2f' % bme_data.humidity
press = '%.2f' % bme_data.pressure
now = datetime.datetime.now() #get time
timeString = now.strftime('%d-%m-%Y %H:%M:%S') #write time to string
return temp, hum, press, timeString
# function to insert data on a table
def logData(temp, hum, press, timeString):
conn = sqlite3.connect(dbname)
curs = conn.cursor()
curs.execute("INSERT INTO BME280_data values((?), (?), (?), (?))", (timeString, temp, hum, press))
conn.commit()
conn.close()
# display data base
def displayData():
conn = sqlite3.connect(dbname)
curs = conn.cursor()
print("\nEntire database contents:\n")
for row in curs.execute("SELECT * FROM BME280_data"):
print(row)
conn.close()
## MAIN
if __name__ == '__main__':
count = 0
dbname = '/home/pi/projects/SmartPlanting/Sensors_Database/sensorsData.db'
sampleFreq = 60 #data collect every minute
while True:
temp, hum, press, timeString = getBMEdata() #get data
logData(temp, hum, press, timeString) #save data
sleep(sampleFreq) #wait
displayData() #show in terminal
#count = count+1
#print(count)
Maybe someone already solved this problem or can give me an alternative to sqlite3 which works with flask.
Suggestion: add a more complete exception handling routine, because your stacktrace could be more verbose.
But judging from your trace the offending line #45 could be this: conn.commit() (or the line above). Python is already helping you pinpoint the error. There is something wrong in function logData.
Could it be that you are feeding incorrect data to your table BME280_data ? To debug your application I would strongly recommend that you print log the data you are trying to insert (use the logging module to output to file and/or console). I don't know the structure of your table but some of your fields could have a definition (data type) that is not compatible with the data you are trying to insert. The fact that you are able to predictably reproduce the problem is quite telling and my hunch is that the data could be the cause.
To sum up: take good habits now and add at least basic exception handling.
A quality application should have exception handling and log errors so they can be reviewed and remediated by a human. This is even more important for unattended applications, because you are not in front of the console and you may not even have a chance to see problems that occur.
Here is one tutorial that may help: https://code.tutsplus.com/tutorials/error-handling-logging-in-python--cms-27932

Python: command line, sys.argv, "if __name__ == '__main__' "

I have a moderate amount of experience using Python in Jupyter but am pretty clueless about how to use the command line. I have this prompt for a homework assignment -- I understand how the algorithms work, but I don't know how to format everything so it works from the command line in the way that is specified.
The prompt:
Question 1: 80 points
Input: a text file that specifies a travel problem (see travel-input.txt
for the format) and a search algorithm
(more details are below).
python map.py [file] [search] should read
the travel problem from “file” and run the “search” algorithm to find
a solution. It will print the solution and its cost.
search is one of
[DFTS, DFGS, BFTS, BFGS, UCTS, UCGS, GBFTS, GBFGS, ASTS, ASGS]
Here is the template I was given:
from search import ... # TODO import the necessary classes and methods
import sys
if __name__ == '__main__':
input_file = sys.argv[1]
search_algo_str = sys.argv[2]
# TODO implement
goal_node = ... # TODO call the appropriate search function with appropriate parameters
# Do not change the code below.
if goal_node is not None:
print("Solution path", goal_node.solution())
print("Solution cost", goal_node.path_cost)
else:
print("No solution was found.")
So as far as python map.py [file] [search] goes, 'file' refers to travel-input.txt and 'search' refers to one of DFTS, DFGS, BFTS,... etc - a user-specified choice. My questions:
Where do I put my search functions? Should they all just be back-to-back in the same block of code?
How do I get the command line to recognize each function from its four or five-letter code? Is it just the name of the function? If I call it just using those letters, how can the functions receive input?
Do I need to reference the input file anywhere in my code?
Does it matter where I save my files in order for them to be accessible from the command line - .py files, travel-input.txt, etc? I've tried accessing them from the command line, with no success.
Thanks for the help!
The function definitions go before the if __name__ == "__main__" block. To select the correct function you can put them in a dict and use the four-letter abbreviations as keys, i.e.
def dfts_search(...):
...
def dfgs_search(...):
....
...
if __name__ == "__main__":
input_file = sys.argv[1]
search_algo_str = sys.argv[2]
search_dict = {"DFTS": dfts_search, "DFGS": dfgs_search, ...}
try:
func = search_dict[search_algo_str]
result = func(...)
except KeyError:
print(f'{search_algo_str} is an unknown search algorithm')
Not sure what you mean by reference, but input_file already refers to the input file. You will need to write a function to read the file and process the contents.
The location of the files shouldn't matter too much. Putting everything in the same directory is probably easiest. In the command window, just cd to the directory where the files are located and run the script as described in the assignment.

Python Coding in Blender

can someone help me solve this problem?
I'm using Blender 2.74 and Python 3.4 with the correct connector for MySQL. (By the way, I'm just a beginner in using Blender and Python.)
What I want is to make a login UI and save the inputted name into the database, but my code seems a bit off or wrong. When I try to run the code, it didn't save the value in the variable, but when i try to run it in python IDE (PyCharm) it worked.
Here's the code:
import sys
sys.path.append('C:\Python34\Lib\site-packages')
sys.path.append('C:\Python34\DLLs')
import mysql.connector
import bge
bge.render.showMouse(1)
cont = bge.logic.getCurrentController()
own = cont.owner
sensor = cont.sensors ["enter"]
pname = own.get("prpText")
enter = cont.sensors ["enter"]
numpadenter = cont.sensors ["numpadenter"]
if enter.positive or numpadenter.positive:
db = mysql.connector.connect(user='root', password='', host='localhost', database='dbname')
cursor = db.cursor()
cursor.execute("INSERT INTO tblname VALUE(%s", (pname))
#this are the other codes that i have tried so far:
#add_player = ("INSERT INTO storymode " "(PlayerName) " "VALUES (%s)")
#data_player = (pname)
#cursor.execute(add_player, data_player)
#cursor.execute("INSERT INTO storymode" "(PlayerName)" "VALUES (%(pname)s)")
db.commit()
db.close()
The Error is:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your mysql server version for the right syntax to use near '%s' at line 1.
Can someone tell what i need to do here? Do I need some add-ons for it to work?
Thank you very much for reading my post and for the people who will give their opinions.
Looks like you're missing a closing parenthesis and an 'S' in you're sql INSERT statement?
INSERT INTO tblname VALUE (%s
needs to be
INSERT INTO tblname VALUES (%s)

Resources