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.
Related
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.
pyzabbix is a module needed for this script to work. I installed it using pip, please see a confirmation below:
WARNING: The script chardetect.exe is installed in 'C:\Users\Christopher Ezimoha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed certifi-2019.11.28 chardet-3.0.4 idna-2.8 pyzabbix-0.7.5 requests-2.22.0 urllib3-1.25.8
C:\Users\Christopher Ezimoha\Desktop>
However, I'm getting an error at line 24 that the module can't be found. I'm not sure what I need to do.
Please see the script below and advise accordingly as I need this code to read a CSV file and update an application called Zabbix.
def addHosts(zapi):
# Add Hosts
file = open('hosts.csv', 'r')
reader = csv.reader(file)
devicelist = list(reader)
import csv
def login():
# Login/authenticate below
session = ZabbixAPI('https://zabbix.xxxxxx.xxx')
# session = ZabbixAPI('http://xxxxxxxxxx/zabbix')
session.login(user="xxxxxxxxxxxx", password="xxxxxxxx")
print("Connected to Zabbix API Version %s" % session.api_version())
return session
for row in devicelist:
device = row[0]
hostgroup = row[1]
responsegroup = zapi.hostgroup.get(filter={'name': hostgroup})
groupid = responsegroup[0]['groupid']
ip = row[2]
templatePriority = row[3]
responsepriority = zapi.template.get(filter={'name': templatePriority})
templatePriorityId = responsepriority[0]['templateid']
# if templatePriority == 'P1':
# templatePriorityId = '40874'
templateType = row[4]
responsetype = zapi.template.get(filter={'name': templateType})
templateTypeId = responsetype[0]['templateid']
try:
response = zapi.host.create(
host=device,
interfaces=[{
'type': 2,
'main': 1,
'ip': ip,
'dns': '',
'port': 161,
'useip': 1
}],
groups=[{
'groupid': groupid}],
templates=[{'templateid': templatePriorityId}, {'templateid': templateTypeId}],
inventory_mode=1
)
print("Created new host: " + device)
except ZabbixAPIException as e:
if 'already exists' in e[0]:
print("Already created host " + device)
else:
print(e[0])
return
def main():
# hostgroup = raw_input('Hostgroup: ')
#hostgroup = "ALTC - Altcar"
zapi = login()
addHosts(zapi)
return
if __name__ == '__main__':
main()
Do you have both python 2 and 3 installed? If you have both, pip installs modules under python2. Try installing like this if you'd like the module to be installed under python3:
pip3 install pyzabbix
There is no import, in the code you included in the question:
from pyzabbix import ZabbixAPI
The login() function should be defined outside of addHosts(), in order to be called like that in main()
I'm currently completing an assignment which requires me to create a script to crack a password from a PDF file, I already have a list which contains the password within, I am having issues when prompt to enter the path to the file and met with an Name not define error, please mind I am a novice to coding.
file = raw_input('Path: ')
wordlist = 'wordlist.txt'
word =open(wordlist, 'r')
allpass = word.readlines()
word.close()
for password in allpass:
password = password.strip()
print ("Testing password: "+password)
instance = dispatch('pdf.Application')
try:
instance.Workbooks.Open(file, False, True, None, password)
print ("Password Cracked: "+password)
break
except:
pass
When the program is running, it attempts the first password from the list then proceeds to crash.
python Comsec.py
Path: /home/hall/Desktop/comsec121/examAnswers.pdf
Testing password: 123456
Traceback (most recent call last):
File "Comsec.py", line 11, in <module>
instance = dispatch('pdf.Application')
NameError: name 'dispatch' is not defined
Please excuse my formatting on this website, I am trying my best to help you understand my issue!
Thanks in advance!
This error means that inside your Python script there is no object or function with the name dispatch. You would get that same error if you tried:
instance = this_is_a_function_that_has_not_been_defined('pdf.Application')
Typically, this function should be defined in a Python module. To access it, at the top of your code you should have some import statement like this:
from aBeautifulModuleForPDFs import dispatch
That module will be providing you the missing dispatch function. Checking in Google, I suggest you to try with module pywin32. Install it (run pip install pywin32 in a terminal) and add this line at the beginning of the code:
from win32com.client import Dispatch as dispatch
I am building a mock terminal-like program using python, and am trying to build a login system for it.
My directory setup, after going through multiple revisions, eventually came out to look like this:
pythonapp-harlker/
__init__.py
loginCheck.py
main.py
userlist.py
__init__.py is empty, and main.py's main code chunk looks like this:
from loginCheck import *
loginFunc = Login()
loginFunc.login()
if loginFunc.login().checkPass == True:
print("Welcome %s!" % (username))
Importing loginCheck returns no error, so naturally, I looked at loginCheck.py.
import sys, platform, importlib
import hashlib
from userlist import *
class Login:
def login(self):
username = input("Username: ")
password = input("Password: ")
password = str.encode(password)
password = str(hashlib.md5(password).hexdigest())
if username in users:
userPassAndIndex = users.get(username)
if password == userPassAndIndex[0]:
checkPass = True
value = userPassAndIndex[1]
else:
self.login()
else:
self.login()
Looking at a debugger, it keeps telling me that loginCheck.py is unable to import a dictionary from userlist.py.
userlist.py
users = {
'localAdmin10': ["086e717a4524329da24ab80e0a9255e2", 0],
'orlovm': ["505ec2b430fa182974ae44ede95ca180", 1],
'testUser10': ["90e611f269e75ec5c86694f900e7c594", 2],
'torradiRemote': ["0b841ebf6393adac25950a215aecc3d1", 3],
}
Additionally, while running the python code (from main.py), the code seems unable to detect if the input username and passwords are correct.
I've looked at tons of stackOverflow pages and external sources but I'm at a kind of "programmer's block" now.
Your code runs fine on Python 3+, and breaks on Python 2.7, let me explain why:
the input function you want to use with Python 2.7 is raw_input, not input. The input function in Python 2.7, evaluates the user input as a Python expression, so in your case, can't find it and send an exception
raw_input was renamed input starting Python 3.0
So to sum it up, you just have to pick the right function depending on which version of Python you'd like to use. raw_inputfor Python 2.7, input for Python 3.
Simple enough, off of my last question, I am trying to make a directory change to a players desktop or file that is similar for all, as in C:\\Users\\USERNAME\\Desktop\\Tester File but the how would I make it so that USERNAME is the username of the person's computer? I tried using %USERNAME% but I don't really know how to do that, and it didn't work, and anyway the % gave an error message (I cannot remember the message, I think it was syntax error)
I also tried using ~, but it proved to be ineffective, but it may be due to my lack of experience.
EDIT
I solved this issue, thanks to some very great help from #pstatix so thank you.
By using user = getpass.getuser() I was able to do something like 'C:\Users' + user + '\Documents' it made this all user friendly! Thanks!
Have you tried the getpass module? getpass documentation here.
import getpass
usr = getpass.getuser()
print usr
Edit: For user specified example
You may also be interested in using the os module? os documentation here.
import os
usr = os.getlogin()
path = os.path.join('..', 'Users', usr, 'Desktop', 'Tester File')
os.chdir(path)
Using os.environ for environment variables may also prove useful. os.environ documentation here For example:
import os
def getUserName():
# set possible environment variables
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
usr = os.environ.get(name)
if user:
return usr #return the variable
if __name__ == '__main__':
usr = getUserName()
# do remainder below