I wrote a very basic script to cleanup my downloads folder and everything worked fine, but I was not using any functions.
To clean things up a bit and make it more organized, I tried to create functions and pass the directory path as a variable "cleaningpath", but I think I am doing something incorrect.
import sys
import os
from os import listdir
from os.path import join
import shutil
#Variables
path="/Users/OwlFace/downloads"
cleaningpath=os.listdir(path)
def deleterars(cleaningpath):
rarcounter=0
for item in cleaningpath:
if item.endswith(".rar"):
os.remove(join(cleaningpath,item))
rarcounter+=1
print "you have succesfully removed", rarcounter, "rar files"
def organizemusic(cleaningpath):
mp3counter=0
if not os.path.exists("/Users/OwlFace/downloads/NewMusic/"):
os.makedirs("/Users/OwlFace/downloads/NewMusic/")
mp3folder="/Users/OwlFace/downloads/NewMusic/"
for item in cleaningpath:
if item.endswith(".mp3"):
location1 = join(cleaningpath,item)
location2 = join(mp3folder,item)
shutil.move(location1, location2)
mp3counter+=1
print "you have succesfully moved", mp3counter, "mp3's to the music folder"
if __name__ == "__main__":
deleterars(cleaningpath)
organizemusic(cleaning path)
Error:
Traceback (most recent call last):
File "cleaningscript.py", line 39, in <module>
organizemusic(cleaningpath)
File "cleaningscript.py", line 30, in organizemusic
location1 = join(cleaningpath,item)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 70, in join
elif path == '' or path.endswith('/'):
AttributeError: 'list' object has no attribute 'endswith'
The error refers to the line:
location1 = join(cleaningpath,item)
This line doesn't work because cleaningpath is a list of file names, not a string. I think you want your global variable path as the first argument to join.
You have the same issue in your other function, on this line:
os.remove(join(cleaningpath,item))
Related
I am creating a trading bot. I have 2 files a settings.json file and a main.py file.
my settings.json file :
`{
"username": "51410030",
"password": "s5p3GI1zY",
"server": "Alpari-MT5-Demo",
"mt5Pathway": "C://Program Files/Alpari MT5/terminal64.exe",
"symbols": ["USDJPY.a"],
"timeframe": "M30"
}
and my main.py file :
import json
import os
import mt5_interface
import strategy
# Function to import settings from settings.json
def get_project_settings(importFilepath):
# Test the filepath to sure it exists
if os.path.exists(importFilepath):
# Open the file
f = open(importFilepath, "r")
# Get the information from file
project_settings = json.load(f)
# Close the file
f.close()
project_settings = list(project_settings)
# Return project settings to program
return project_settings
else:
return ImportError
# Main function
if __name__ == '__main__':
# Set up the import filepath
import_filepath = "C:/Users/james/PycharmProjects/how_to_build_a_metatrader5_trading_bot_expert_advisor/settings.json"
# Import project settings
project_settings = get_project_settings(import_filepath)
# Start MT5
mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"],
project_settings["mt5Pathway"])
# Initialize symbols
mt5_interface.initialize_symbols(project_settings["symbols"])
# Select symbol to run strategy on
symbol_for_strategy = project_settings['symbols'][0]
# Start strategy one on selected symbol
strategy.strategy_one(symbol=symbol_for_strategy, timeframe=project_settings['timeframe'],
pip_size=project_settings['pip_size'])
my prblem is when i run my main.py file it gives me this error:
Traceback (most recent call last):
File "i:\Traiding Bot\code\main.py", line 32, in <module>
mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"],
TypeError: 'type' object is not subscriptable
please help me.
I couldn't find a solution please help me.
There are a few issues with your code:
You're trying to access fields in a list. That's not possible, you should keep your list a dictionary if you want access its fields.
You're returning an ImportError, if you want to raise an error, use raise ImportError("Your error message"). Or if you want to catch the error, use a try: <your code> except: return None and then check if you're returning None or not.
I am trying to use a sqlite3 database in python but I get the following error:
Traceback (most recent call last):
File "C:\Users\Angel\Desktop\Proyecto\Src_School_Admin\SchoolAdmin-Director.py", line 4, in <module>
from execute_files.Sqlitedb import FirstUseInfo
File "C:\Users\Angel\Desktop\Proyecto\Src_School_Admin\execute_files\Sqlitedb.py", line 17, in <module>
FirstUseInfo()
File "C:\Users\Angel\Desktop\Proyecto\Src_School_Admin\execute_files\Sqlitedb.py", line 12, in FirstUseInfo
s = cursor.execute("SELECT Use FROM MainData")
sqlite3.OperationalError: no such table: MainData
[Finished in 0.2s]
The FirstUseInfo function is located in a file in the following path:C:\Users\Angel\Desktop\Project\Src_School_Admin\execute_files together with the database
and the file that sends to call the FirstUseInfo function is inC:\Users\Angel\Desktop\Project\Src_School_Admin
but it does not work keeps marking the error
First.py
from PyQt5.QtWidgets import QMainWindow,QApplication
from PyQt5 import uic
from PyQt5 import QtCore
from execute_files.Sqlitedb import FirstUseInfo
class InitWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
#uic.loadUi("UIX/first.ui",self)
#self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
#self.LStatus.setText("Cargando...")
self.FirstUse()
FirstUseInfo()
def FirstUse(self):
pass
app = QApplication([])
iw = InitWindow()
iw.show()
app.exec_()
Sqlitedb.py
import sqlite3
from PyQt5.QtWidgets import QMessageBox
import os
def FirstUseInfo():
r = str(os.getcwd())
final = r.replace("\\","/")
result = None
d=final+"/InfoDB.db"
conexion = sqlite3.connect(d)
cursor = conexion.cursor()
s = cursor.execute("SELECT Use FROM MainData")
for i in s:
result = int(i[0])
return print(result)
conexion.close()
FirstUseInfo()
if I run FirstUseInfo () from Sqlitedb.py there is no problem but if I execute it from another side it throws the error.
I realized that for some reason another database is created in the directory C: \ Users \ Angel \ Desktop \ Project \ Src_School_Admin, which is where the file that sends to call theFirstUseInfo function is located
but if I execute it from another side it throws the error.
So your code
r = str(os.getcwd())
final = r.replace("\\","/")
result = None
d=final+"/InfoDB.db"
gives new filename every time you are running program from somewhere else.
When you run
conexion = sqlite3.connect(d)
SQLite doesn't see the database and it creates there.
You should make some variable where you will store real filename for your database file.
solve it by attaching this line of code
r = os.path.dirname (__ file __)
source = r.replace ('\\'," / ") +" / InfoDB.db "
as I understand this line returns the absolute value of the location of the file
I am creating a tageditor that displays the ID3-Tags of an mp3 file in a "before" "after" style in different textLines. If there's no tag available, nothing is displayed. You are also able to edit the "after" textLines and any changes made to them should be saved to the file but when I press button2 I am getting the bottom traceback. How can I save the lines6-10 as the new "audio["title"], audio["artist"]" etc? This is the GUI
import sys
import easygui
import mutagen
from mutagen.easyid3 import EasyID3
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QLineEdit
lied = None
error = "No ID3-Tag available."
class TrackTag1(QDialog):
def __init__(self):
super(TrackTag1,self).__init__()
loadUi("TrackTag1.ui",self)
self.setWindowTitle("TrackTag")
#pyqtSlot()
def on_button1_clicked(self):
#root.fileName = filedialog.askopenfilename( filetypes = ( ("Musik Dateien", "*.mp3"), ("Alle Dateien", "*.*") ) )
#print(easygui.fileopenbox('MP3 Dateien','', '*.MP3'))
lied = easygui.fileopenbox('MP3 Dateien','', '*.MP3')
audio = EasyID3(lied)
self.line0.setText(lied) #printing filepath to line0
try:
self.line1.setText(str(audio["title"]).strip("[']")) #printing the ID3 tags after they've been stripped of "['']"
self.line6.setText(str(audio["title"]).strip("[']"))
except:
KeyError
self.line1.setText(error)
try:
self.line2.setText(str(audio["album"]).strip("[']"))
self.line7.setText(str(audio["album"]).strip("[']"))
except:
KeyError
self.line2.setText(error)
try:
self.line3.setText(str(audio["date"]).strip("[']"))
self.line8.setText(str(audio["date"]).strip("[']"))
except:
KeyError
self.line3.setText(error)
try:
self.line4.setText(str(audio["artist"]).strip("[']"))
self.line9.setText(str(audio["artist"]).strip("[']"))
except:
KeyError
self.line4.setText(error)
try:
self.line5.setText(str(audio["genre"]).strip("[']"))
self.line10.setText(str(audio["genre"]).strip("[']"))
except:
KeyError
self.line5.setText(error)
def on_button2_clicked(self):
audio = EasyID3(lied)
audio["title"] = self.line6.text()
audio.save()
app=QApplication(sys.argv)
widget=TrackTag1()
widget.show()
sys.exit(app.exec_())
app=QApplication(sys.argv)
widget=TrackTag1()
widget.show()
sys.exit(app.exec_())
I'm getting this traceback when I press the save changes button:
Traceback (most recent call last):
File "<string>", line 69, in on_button2_clicked
File "h:\program files (x86)\python\lib\site-packages\mutagen\_util.py", line 139, in wrapper
writable, create) as h:
File "h:\program files (x86)\python\lib\contextlib.py", line 59, in __enter__
return next(self.gen)
File "h:\program files (x86)\python\lib\site-packages\mutagen\_util.py", line 270, in _openfile
raise TypeError("Missing filename or fileobj argument")
TypeError: Missing filename or fileobj argument
For now, you should only be able to edit the tags but I am planning to implement a MusicBrainz query soon.
In the method on_button2_clicked the lied object is basically None.
To get the correct one, use the keyword global when assigning it in on_button1_clicked. (Which you actually never should! Instead make an attribute to store it and access it via self.lied or something similar)
Also, I am assuming that the two functions are infact class methods owing to the self keyword and you simply got the indentation wrong while copy pasting.
Basically an error due to scopes.
The function below works just fine. But if I remove all py files (and leave the pycs intact) then I get an error:
To explain what I mean by 'intact' here is more or less what I did:
1. write a bunch of py files and stick them in a friendly directory structure
2. test code code. It works
3. compile all py files to get pyc files
4. delete py files
5. test code. It fails
The function:
def get_module_name_and_line():
"""
return the name of the module from which the method calling this method was called.
"""
import inspect
lStack = inspect.stack()
oStk = lStack[2]
oMod = inspect.getmodule(oStk[0])
oInfo = inspect.getframeinfo(oStk[0])
sName = oMod.__name__ #<<<<<<<<<<<<<<<<<< ERROR HERE
iLine = oInfo.lineno
return sName,iLine
The error:
AttributeError: 'NoneType' object has no attribute '__name__'
So oMod is None in this error. If the py files are around then oMod is never None.
The question:
Why does inspect only return a module if py files are intact? How can I make this function work without py files.
Full Traceback:
Original exception was:
Traceback (most recent call last):
File "/home/criticalid/programs/damn.py", line 630, in <module>
File "/home/criticalid/programs/golly/class_foo.py", line 121, in moo
File "/home/criticalid/programs/golly/class_foo.py", line 151, in get_module_name_and_line
AttributeError: 'NoneType' object has no attribute '__name__'
This works for me. It assumes that all modules are in packages within the current working directory. And it doesn't return the __main__ module, rather its file name.
I'm sure there is a better solution but this solves my problems.
def get_module_name_and_line():
"""
return the name of the module from which the method calling this method was called.
"""
def get_name_from_path(sPath):
import os
sCWD = os.getcwd()
lCWD = list(os.path.split(sCWD))
lPath = list(os.path.split(sPath))
lPath[-1] = '.'.join(lPath[-1].split('.')[:-1]) #remove file extension
lRet = [s for s in lPath[len(lCWD)-1:]]
return '.'.join(lRet)
import inspect
lStack = inspect.stack()
oStk = lStack[2]
iLine = inspect.getlineno(oStk[0])
sName = get_name_from_path(inspect.getfile(oStk[0]))
return sName,iLine
I am using VBA in conjunction with Python.
I imported the module OS, and for working with excel - openpyxl. The problem occurs when it iterates the function for running the VBA macro from Excel.
import random
from openpyxl import load_workbook
import os, os.path, win32com.client
wbi = load_workbook('Input.xlsm')
wsi = wbi.get_active_sheet()
wbo = load_workbook('Output.xlsx')
wso = wbo.get_active_sheet()
def run_macro(fName, macName, path=os.getcwd()):
"""
pre: fName is the name of a valid Excel file with macro macName
post: fName!macName is run, fName saved and closed
"""
fName = os.path.join(path, fName)
xlApp = win32com.client.Dispatch("Excel.Application")
fTest = xlApp.Workbooks.Open(fName)
macName = fTest.Name + '!' + macName
xlApp.Run(macName)
fTest.Close(1)
xlApp.Quit()
xlApp = None
def IBP():
ibp = wsi.cell('G12')
ibpv = random.randint(0,45)
ibp.value = ibpv
return ibp.value
def BP10():
bp10 = wsi.cell('G13')
bpv10 = random.randint(30,50)
bp10.value = bpv10
return bp10.value
for n in range(6):
IBP()
print IBP()
BP10()
run_macro('Input.xlsm','macro1')
wbo.save('Output.xlsx')
I think that the error is in run_macro('Input.xlsm','macro1') - it cannot iterate.
The output:
Qt: Untested Windows version 6.2 detected!
35
4
Traceback (most recent call last):
File "C:\Users\User\Desktop\Python Exp\Pr 1.py", line 77, in <module>
run_macro('Input.xlsm','macro1')
File "C:\Users\User\Desktop\Python Exp\Pr 1.py", line 18, in run_macro
fTest = xlApp.Workbooks.Open(fName)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Excel.Application.Workbooks
What am I doing wrong?
I'm not sure this will help, but you can try early binding. Run this script and then try yours again:
import win32com.client
xl = win32com.client.gencache.EnsureDispatch ("Excel.Application")
print xl.__module__
If that does not work, you can alway go back to late binding by hooking to Excel like this:
xl = win32com.client.dynamic.Dispatch("Excel.Application")
or by simply deleting this folder: C:\Python27\Lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x7
From the error message, it looks like your problem is on the line wb = xlApp.Workbooks.Open(fname). If the Python hooks to the Excel com servers were working correctly, then that line would not raise the exception that it did. I don't see anything wrong with the code where the exception occured. Sometimes early binding helps in situations like this.
good luck
Mike