NameError: name 'permutations' is not defined - python

This is a script that generates password dictionary for guessing a password.
I'm getting this error:
Traceback (most recent call last):
File "pass.py", line 19, in <module>
for p in permutations(stuff, x):
NameError: name 'permutations' is not defined
Code:
#!/usr/bin/python
# define the prefix to try since we knew what the password starts with
prefix = ['begin', 'Begin']
# list of sequences to run through
sequences = ['seq1', 'Seq1', 'SEQ1', 'se2', '!', '123', '555', '103', '_']
# open the password file where the dictionary will be saved
newfile = open('mypass.txt', 'w')
# A python3 thing I guess
stuff = list(sequences)
# Generate permutations of the password, starting wth the prefix and then 2 to 6 combos of the "charset"
for i in prefix:
for x in range(2,6):
for p in permutations(stuff, x):
newfile.write(''.join(p) + '\n')
Example output:
beginseq1SEQ1
begin_seq1
Begin_seq1103

This permutations is probably a function from another file or from a package. Probably you are a new python user and have forgotten to state at the top of your code to which file or package you refer. You have to add a line that looks like this, if you import from a file:
from some_code_file.py import some_function
or like this, if you import a package:
import python_package as py_pa
And than your code should work as you have writen it. Or just alter to the form some_function.permutations(stuff,x) or py_pa.permtations(stuff,x)

Related

ImportError "text_process" Python library

I'm taking a look at some CBOW Python implementations.
The owner of the code used a function called "line_processing" from text_process lib.
When I tried to run, I got that error:
ImportError: cannot import name 'line_processing' from 'text_process'
So I took a look at the lib implementation. There is no function called "line_processing".
That guy used this function to read each line from a .txt file, and write them in a variable, creating a "big string":
text = 'file.txt'
print(text)
text = ''
count = 0
for i in open(text_file, 'r', encoding='utf-8'):
text+=line_processing(i)+'\n'
count += 1
if count % 10000 == 0: break
Is there anyone who knows something about "line_processing" function, or about a function/lib I can use instead?
Thank you!
Ps.:
$ python CBOW.py
Building prefix dict from the default dictionary ...
Dumping model to file cache C:\"path_to"\AppData\Local\Temp\jieba.cache
Loading model cost 0.723 seconds.
Prefix dict has been built successfully.
Traceback (most recent call last):
File "CBOW.py", line 1, in <module>
from text_process import line_processing
ImportError: cannot import name 'line_processing' from 'text_process' (C:\"path_to"\miniconda3\lib\site\...\text_process)

Function to open and read a file in Python comes up with an error: NameError: name 'xxxx' is not defined

G'day all! I have this project to check if the user input data is in the file. It's all working on a Jupyter notebook but when I created a function def, I keep getting an error: NameError: name 'fread' is not defined.
Here is the folder structure:
main_code
initial_list
user_input
validate_user_input
The issue I believe is coming from the validate_user_input code:
def check_input():
for line in fread:
if ui in line.split():
return line
Here is the initial_list code:
def initial_list():
with open('test', mode='r+') as fopen:
fread=fopen.readlines()
return fread
Here is the user_input code:
def user_input():
ui=input('Enter name here: ')
return ui
And here is the main_code code:
from initial_list import initial_list
from user_input import user_input
from validate_user_input import validate_user_input
initial_list.initial_list()
user_input.user_input()
validate_user_input.check_input()
Note:
all folders contain a init.py to call the function
running the main_code.py enables me to input data (user_input)
tried searching this online but no luck...crying...
Please help, Thank you in advance!
Add the variable fread as input to your function:
def check_input(fread):
for line in fread:
if ui in line.split():
return line
And then when you run the function initial_list(), it should have an output that is the fread input for the other one, like this.
myfread = initial_list()
check_input(myfread)

Python script doesnt work in differents virtual machines

I have a script that clean logs in determinate path.
This script works in one virtual machine but when i export to another one, this script doesn't work. The versions of python are the same:
[ec2-user#host1 h]$ python3 --version
Python 3.5.1
The error:
Traceback (most recent call last):
File "jenk.py", line 54, in <module>
dicta = dict(path)
File "jenk.py", line 51, in dict
dicto[elem] = { (dirs['Subdir'][elem]['Path']) : (dirs['Subdir'][elem]['Num_Subdir']) }
KeyError: 'Path'
This is the code:
def PathToDict(path):
st = os.lstat(path)
result = {}
if S_ISDIR(st.st_mode):
result['Path'] = path
result['Subdir'] = {
name: PathToDict(path+'/'+name)
for name in os.listdir(path)}
result['Num_Subdir'] = int(len([i for i, j, k in os.walk(path)]))
# result['RealSize'] = subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')
else:
result['type'] = 'file'
return result
dirs = PathToDict(path)
#Getting new dict with clean info with name of dir and number of dirs
def dict(path):
dicto = {}
for elem in dirs['Subdir']:
dicto[elem] = { (dirs['Subdir'][elem]['Path']) : (dirs['Subdir'][elem]['Num_Subdir']) }
return dicto
Any idea? COuld be problem of modules?
there is not 'Path' in elem.
Try to debug
print(dirs['Subdir'][elem])
or use
dirs['Subdir'][elem].get('Path')
One thing that might make stuff os dependent is that you manually join a file path in
name: PathToDict(path+'/'+name)
However, that '/' might not be valid on all devices. Instead it is better to use the os.path module in python to join paths. This will automatically select the correct separator.
name: PathToDict(os.path.join(path,name))
This would at least make that part of the code platform independent.
Additionally, passing your input through os.path.normpath will make sure that the input gets correctly parsed to something that is readable on your platform.

How to pass a variable to a function in this example?

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))

Python: What does _("str") do?

I see this in the Django source code:
description = _("Comma-separated integers")
description = _("Date (without time)")
What does it do? I try it in Python 3.1.3 and it fails:
>>> foo = _("bar")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
foo = _("bar")
NameError: name '_' is not defined
No luck in 2.4.4 either:
>>> foo = _("bar")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
foo = _("bar")
NameError: name '_' is not defined
What's going on here?
The name _ is an ordinary name like any other. The syntax _(x) is calling the function called _ with the argument x. In this case it is used as an alias for ugettext, which is defined by Django. This function is used for translation of strings. From the documentation:
Specifying translation strings: In Python code
Standard translation
Specify a translation string by using the function ugettext(). It’s convention to import this as a shorter alias, _, to save typing.
To use _ in your own code you can use an import like this:
from django.utils.translation import ugettext as _
The symbol _ is just a variable name in python, and in this case it looks like it refers to a function or other "callable" which takes a string as an argument. For example
def myfun(strng):
return "input = " + strng
_ = myfun
description = _("Comma-separated integers")
It should be noted that you cannot choose any alias to want, if you want ``makemessages```to detect the strings.

Categories

Resources