Unable to import a file in python - python

I want to import a file in a local directory but python refused to do so and it gives error everytime i do so.
I tried putting "from Admin_login import Admin_login" but it gives an error saying
"ModuleNotFoundError: No module named 'Admin_login'"
my code:-(main.py)
from .Admin_login import Admin_login
loggsin = Admin_login.login()
if loggsin == True:
print("You are logged in")
This is the Admin_login.py file
import json
import os
def load_data():
with open("data.json", "r") as f:
Data = json.load(f)
return Data
class Admin_login():
def login(self):
Login = False
while Login == False:
id = input("Enter the id you want to login = ")
data = load_data()
if id == data["id"]:
print(data["name"])
passord = input("Enter the password = ")
if passord == data["password"]:
print("You are successfully logged in")
Login = True
return Login
os.system('cls')
else:
print("The id doesn't exist... Please try again!")
Login = False
return Login
os.system('cls')
if __name__ == '__main__' :
Admin_login()
and the error it gives is :-
Traceback (most recent call last):
File "C:\Users\myUser\Desktop\LibApp\main.py", line 1, in <module>
from .Admin_login import Admin_login
ImportError: attempted relative import with no known parent package
pls help

My best guess is that the '.' is giving you the trouble. When you add a dot to a directory name, it is referring to a relative directory and not an absolute one. That's what that error you're getting is referring to. If those two files are in the same directory, you can just remove the dot and it should work.

Related

TypeError: 'type' object is not subscriptable, error when creating an trading bot with python

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.

When importing a module in jupyter and executing a function manually, cell returns "error module has no attribute"

I am trying to collect my main functions in a separate .py module, that I am importing in my Juptyer Notebook. So I can call a function when I need it. I would like to keep this simple, as I am a beginner in Python.
I have 2 main problems:
When I import the db.py module in my Jupyter notebook, all def functions are executed.
I read this is normal in Python and it can be prevented by placing if __name__ == "__main__": before the functions I want to execute manually. And it seems to work.
However, if I add the code above, when I run the functions manually, I get this other error
module 'ch_db' has no attribute 'get_data'
Any suggestion?
db.py - this is the file where i would like to collect my functions
def main():
print('Credentials required')
print('Enter User:')
pass_user = getpass.getpass()
print('Enter db pssw:')
pass_clickhouse = getpass.getpass()
if __name__ == "__main__":
def get_data():
# ... some other code to get data from database ...
df_ch = pd.DataFrame(result)
return df_ch
df_ch = get_data()
def seg_data():
seg_startdate = input('Enter start date (yyyy-mm-dd): ')
seg_finishdate = input('Enter end date (yyyy-mm-dd): ')
df_ch_seg = df_ch[(df_ch['event_datetime'] > seg_startdate)
& (df_ch['event_datetime'] < seg_finishdate)]
return df_ch_seg
df_ch_seg = seg_data()
In Jupyter Notebook:
In[1]: import ch_db
In[2]: db.get_data()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-78c2ac644f6e> in <module>
----> 1 ch_db.get_data()
AttributeError: module 'db' has no attribute 'get_data'

Trying to connect files to my main.py file, gives me an error

I've been trying out python for the past few days and have been coding a basic terminal thingy for fun. I decided to move my functions to other files and use the import feature to connect them. My IDE (repl.it) tells me I can just import the filename and call the functions in my main.py, but the built-in interpreter gives me a NameError. Here's my code:
main.py
import functions
def terminal() :
command = input('')
if command == 'login' :
functions.login()
if command == 'logout' :
functions.logout()
if command == 'info' :
info.info()
print('Welcome to the terminal. Please start by entering a command.')
terminal()
functions.py
import main
def login() :
enteredcode = input('Enter Passcode: ')
if enteredcode == code[0] :
loggedIn == True
print('Login Successful!')
print('Logged in as: ' + user[0])
main.terminal()
if enteredcode == code[1] :
loggedIn == True
print('Login Successful!')
print('Logged in as: ' + user[1])
main.terminal()
else :
print('Incorrect Code. Please Try Again.')
login()
def logout() :
if loggedIn == True :
loggedIn == False
print('Logged Out.')
main.terminal()
return
elif loggedIn == False :
print('You are already logged out.')
main.terminal()
user = ['user1', 'user2']
code = ['2001', '6969']
loggedIn = False
And here's the error:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import functions
ModuleNotFoundError: No module named 'functions'
UPDATE: Fixed! I think it was the circular import that messed it up.
Your code has several issues beyond the circular imports; I took the liberty of cleaning it up a little.
You need to use the global keyword before reading global variables if you intent to modify them. You can sometimes get by without this but it's always better to be explicit. Even better would be not relying on globals at all by encapsulating state within an object, but that can be a future exercise.
You appear to be using == where you intend to be assigning; you just need a single = for that.
You can just loop forever with a while in your terminal function instead of recursively calling back and forth between terminal and login/logout -- that will just end up blowing your call stack.
Your user codes are a great place to learn about how dictionaries work.
I added an exit command as well as a warning if you try to login when already logged in.
Here:
#main.py
import functions
def terminal() :
while True:
command = input('>> ')
if command == 'login' :
functions.login()
elif command == 'logout' :
functions.logout()
elif command == 'exit':
print("Goodbye!")
break
else:
print("Unknown command!")
print('Welcome to the terminal. Please start by entering a command.')
terminal()
And:
# functions.py
users_by_code = {
'2001': 'user1',
'6969': 'user2',
}
loggedIn = False
def login() :
global loggedIn
if loggedIn:
print('You are already logged in!')
return
while True:
enteredcode = input('Enter Passcode: ')
user = users_by_code.get(enteredcode)
if user:
break
print('Incorrect Code. Please Try Again.')
loggedIn = True
print('Login Successful!')
print('Logged in as:', user)
def logout():
global loggedIn
if loggedIn:
loggedIn = False
print('Logged Out.')
else:
print('You are already logged out.')
Instead of import functions, try from functions import *

Python - Download files from Share Point | Authentication token error

I am working on a report automation project, where I need to download excel files automatically from a share point location. I tried some examples referring to Python - Download files from SharePoint site but getting below error within imported library function. Please let me know, what I am missing here.
Error:
Traceback (most recent call last):
File "worklod_report.py", line 66, in
if ctxAuth.acquire_token_for_user(username='murali.pandiyan#xyz.com', password=pwd):
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\office365\runtime\auth\authentication_context.py", line 18, in acquire_token_for_user
return self.provider.acquire_token()
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\office365\runtime\auth\saml_token_provider.py", line 57, in acquire_token
self.acquire_service_token(options)
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\office365\runtime\auth\saml_token_provider.py", line 88, in acquire_service_token
token = self.process_service_token_response(response)
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\office365\runtime\auth\saml_token_provider.py", line 119, in process_service_token_response
return token.text
AttributeError: 'NoneType' object has no attribute 'text'
Python code:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
import getpass
if __name__ == '__main__':
ctxAuth = AuthenticationContext(url='https://internal.abc.net/sites/Compute/')
print("Enter Password:")
pwd=getpass.getpass()
if ctxAuth.acquire_token_for_user(username='murali.pandiyan#xyz.com', password=pwd):
ctx = ClientContext(settings['url'], ctxAuth)
print("Authentication is success")
else:
print(ctxAuth.get_last_error())
The following code snippet for your reference.
if __name__ == '__main__':
ctxAuth = AuthenticationContext('https://internal.abc.net/sites/Compute/')
print("Enter Password:")
pwd=getpass.getpass()
if ctxAuth.acquire_token_for_user('murali.pandiyan#xyz.com', pwd):
ctx = ClientContext(settings['url'], ctxAuth)
print("Authentication is success")
else:
print(ctxAuth.get_last_error())
Check the authentication source code here: authentication_context.py
And the source code of file download is here: file_operations.py

Syntax invalid?

For some reason I keep getting an invalid syntax error of my code on Debian. But when I run it on my mac nothing wrong happens and it runs smooth. Could you guys help me?
def read_config(cfg='~/instacron/config.txt'):
"""Read the config.
Create a config file at `cfg` with the
following information and structure:
my_user_name
my_difficult_password
"""
import os.path
_cfg = os.path.expanduser(cfg)
try:
with open(_cfg, 'r') as f:
user, pw = [s.replace('\n', '') for s in f.readlines()]
except Exception:
import getpass
print(f"\nReading config file `{cfg}` didn't work")
user = input('Enter username and hit enter\n')
pw = getpass.getpass('Enter password and hit enter\n')
save_config = input(
f"Save to config file `{cfg}` (y/N)? ").lower() == 'y'
if save_config:
os.makedirs(os.path.dirname(_cfg), exist_ok=True)
with open(_cfg, 'w') as f:
f.write(f'{user}\n{pw}')
return {'username': user, 'password': pw}`
print(f"\nReading config file `{cfg}` didn't work")
^
SyntaxError: invalid syntax
f-strings (f"{var}") were only added to Python in version 3.6; earlier versions do not accept them. Your Debian and Mac are clearly running different versions of Python, only one of which is at least 3.6.

Categories

Resources