I'm beginner in Python. I'm using multi-processing to batch program such as xcopy from host PC to remote PCs. I got a permissionerror such as *DUPLICATE_SAME_ACCESS*. any help would be very helpful.
IDE Env. :
Kepler
Python-3.x
error message
Traceback (most recent call last):
File "C:\Users\Administrator\.eclipse\org.eclipse.platform_4.3.0_1709980481_win32_win32_x86_64\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1446, in <module>
debugger.run(setup['file'], None, None)
File "C:\Users\Administrator\.eclipse\org.eclipse.platform_4.3.0_1709980481_win32_win32_x86_64\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1092, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "C:\Users\Administrator\.eclipse\org.eclipse.platform_4.3.0_1709980481_win32_win32_x86_64\plugins\org.python.pydev_2.8.2.2013090511\pysrc\_pydev_execfile.py", line 38, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script
File "C:\Users\Administrator\Documents\Kepler\workspace\kr.caleb.python.first\src\fileCopy\xCopyPython.py", line 92, in <module>
dist_files(server_list, 'C:\\Users\\Public\\jvision')
File "C:\Users\Administrator\Documents\Kepler\workspace\kr.caleb.python.first\src\fileCopy\xCopyPython.py", line 79, in dist_files
Process(target=multi_distribute_file,args=(lock, server, dirpath, filename, path)).start()
File "C:\Python33\lib\multiprocessing\process.py", line 111, in start
self._popen = Popen(self)
File "C:\Python33\lib\multiprocessing\forking.py", line 248, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python33\lib\multiprocessing\forking.py", line 166, in dump
ForkingPickler(file, protocol).dump(obj)
File "C:\Python33\lib\multiprocessing\synchronize.py", line 70, in __getstate__
return (Popen.duplicate_for_child(sl.handle), sl.kind, sl.maxvalue)
File "C:\Python33\lib\multiprocessing\forking.py", line 258, in duplicate_for_child
return duplicate(handle, Popen._tls.process_handle)
File "C:\Python33\lib\multiprocessing\forking.py", line 201, in duplicate
0, inheritable, _winapi.DUPLICATE_SAME_ACCESS
PermissionError: [WinError 5] Access is denied
Full code (xCopyPython.py) :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# based on Carnival http://ask.python.kr/users/6970/carnival/
import os, sys, csv, re
from multiprocessing import Process, Lock
class Server:
def __init__(self, addr, path):
self.addr = addr
self.path = path
def multi_distribute_file(lo, server, dirpath, filename, subdir):
lo.acquire()
pathname = os.path.join(dirpath, filename)
print("Read from {}".format(pathname))
with open(pathname, 'rb') as inFile:
buffer = inFile.read()
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
remotepath = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
remotepath += "/%s" % (m[cnt_l + j])
remotepath += "/%s" % (filename)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
lo.release()
def make_dir(server_list, subdir, dirpath):
for server in server_list:
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
path = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
path += "/%s" % (m[cnt_l + j])
d = os.path.dirname(path)
if not os.path.exists(d):
os.makedirs(d)
print ("Make dir {}".format(d))
else:
print ("dir {} already exists.".format(d))
if not os.path.exists(path):
os.makedirs(path)
print ("Make dir {}".format(path))
else:
print ("dir {} already exists.".format(path))
def dist_files(server_list, subdir):
for dirpath, dirnames, filenames in os.walk(subdir):
make_dir(server_list, subdir, dirpath)
for filename in filenames:
for server in server_list:
lock = Lock()
Process(target=multi_distribute_file,args=(lock, server, dirpath, filename, subdir)).start()
def get_server_list(filename):
mydictionary = []
csvFile = csv.reader(open(filename, "r"))
for row in csvFile:
mydictionary.append(Server(row[0], row[1]))
print("{}, {}".format(row[0], row[1]))
return mydictionary
if __name__ == '__main__':
server_list = get_server_list('client_list.csv')
dist_files(server_list, 'C:\\Users\\Public\\Test')
client.csv :
192.168.10.100, Test
192.168.10.101, Test
192.168.10.102, Test
I'm going to modify multi_distribute_file method to open/read file.
origin :
def multi_distribute_file(lo, server, dirpath, filename, subdir):
lo.acquire()
pathname = os.path.join(dirpath, filename)
print("Read from {}".format(pathname))
with open(pathname, 'rb') as inFile:
buffer = inFile.read()
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
remotepath = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
remotepath += "/%s" % (m[cnt_l + j])
remotepath += "/%s" % (filename)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
lo.release()
modify : buffer arg is added.
def multi_distribute_file(server, dirpath, filename, subdir, buffer):
#lo.acquire()
#pathname = os.path.join(dirpath, filename)
#print("Read from {}".format(pathname))
#with open(pathname, 'rb') as inFile:
# buffer = inFile.read()
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
cnt_l = len(l)
cnt_m = len(m)
remotepath = "//%s/%s" % (server.addr, server.path)
if(cnt_m > cnt_l):
for j in range(cnt_m - cnt_l):
remotepath += "/%s" % (m[cnt_l + j])
remotepath += "/%s" % (filename)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
#lo.release()
Related
I am getting an error while encrypting a file.
C:\Users\username>python xor_encryptor.py raw.txt > new.txt
Traceback (most recent call last):
File "C:\Users\username\xor_encryptor.py", line 19, in <module>
ciphertext = xor(plaintext, KEY)
File "C:\Users\username\xor_encryptor.py", line 10, in xor
output_str += chr(ord(current) ^ ord(current_key))
TypeError: ord() expected string of length 1, but int found
The xor_encryptor script is:
import sys
KEY = "x"
def xor(data, key):
key = str(key)
l = len(key)
output_str = ""
for i in range(len(data)):
current = data[i]
current_key = key[i % len(key)]
output_str += chr(ord(current) ^ ord(current_key))
return output_str
def printCiphertext(ciphertext):
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
try:
plaintext = open(sys.argv[1], "rb").read()
except:
print("File argument needed! %s " % sys.argv[0])
sys.exit()
ciphertext = xor(plaintext, KEY)
print('{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in ciphertext) + ' };')
Kindly give an appropriate solution.
EDIT: I wonder if you think the issue might be that I'm trying to store an entire dictionary row returned from database in a session variable?
Here's the error (full error printout is at bottom of this post):
TypeError: Object of type User is not JSON serializable
FYI: I'm not using JSON anywhere in my code.
Here's the relevant parts of my code (main.py):
class User():
def __init__(self, t_id_user=None, t_email=None):
self.t_id_user = t_id_user
self.t_email = t_email
def create_or_update(self, t_create_or_edit="Edit"):
#How necessary are the "=None" below?
#self.t_id_user = userCreate(self, t_id_user=None, t_email=None):
#How necessary are the "=None" above?
if t_create_or_edit == "Create":
self.t_id_user = userCreate(
self.t_email
)
else:
self.t_id_user = userUpdate(
self.t_id_user_edit,
self.t_email
)
def get_from_id(self, t_id_user):
# logic to retrieve your user's data from your database of choice
myData = usersGet(
t_id_user="0",
t_email=""
)
self.t_id_user = myData["t_id_user"]
self.t_email = myData["t_email"]
return self
def userClearSession(t_which="user_current"):
logging.debug("Start of userClearSession()")
t_id_user = "0"
t_email = ""
user_instance = User(t_id_user, t_email)
if t_which == "user_current":
session["user_current"] = user_instance
else:
session["user_edit"] = user_instance
return
#app.route('/', methods=['GET', 'POST'])
#app.route('/userRegister', methods=['GET', 'POST'])
def index(t_title="Login or Register", t_message=""):
if "user_current" not in session:
userClearSession(t_which="user_current")
return render_template(
"userRegister.html",
t_message=t_message,
t_js="userRegister.js",
t_title=t_title
)
def userCreate(t_which="current"):
id_user = 0
db_cursor = data_cursor()
q = ""
q += "INSERT INTO tbl_users "
q += " ( "
q += " i_security_level"
q += ", t_email"
q += " ) "
q += " VALUES "
q += " ( "
q += " %(t_security_level)s"
q += ", '%(t_email)s'"
q += " ) "
try:
if t_which == "current":
user_instance = session["user_current"]
else:
user_instance = session["user_edit"]
vars = {
't_security_level': int(session["user_instance"].t_security_level),
't_email': AsIs(session["user_instance"].t_email)
}
db_cursor.execute(q,vars)
except Exception as e:
t_message = "Error"
else:
id_found = userIsInDB(session["user_instance"].t_email)
if id_found >= 1:
t_id_user = id_found
if t_which == "current":
session["user_current"].t_id_user = t_id_user
else:
session["user_edit"].t_id_user = t_id_user
t_message = "User Created"
db_cursor.close()
db_conn.close()
The full error message:
I'm having a hard time getting any meaning out of this error message and need help. It doesn't appear to point to any parts of main.py, though I know the error is somewhere in there and I'm pretty sure I narrowed it down to the code you see above:
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 1970, in finalize_request
response = self.process_response(response)
File "C:\Python\Python38\Lib\site-packages\flask\app.py", line 2269, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "C:\Python\Python38\Lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "C:\Python\Python38\Lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "C:\Python\Python38\Lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "C:\Python\Python38\Lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Python\Python38\Lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Python\Python38\Lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python\Python38\Lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python\Python38\Lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "C:\Python\Python38\Lib\json\encoder.py", line 179, in default
Open an interactive python shell in this frameraise TypeError(f'Object of type {o.__class__.__name__}
I am trying to execute the codes from this link
https://zulko.github.io/blog/2014/06/21/some-more-videogreping-with-python/
import re # module for regular expressions
def convert_time(timestring):
""" Converts a string into seconds """
nums = map(float, re.findall(r'\d+', timestring))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
with open("Identity_2003.srt") as f:
lines = f.readlines()
times_texts = []
current_times , current_text = None, ""
for line in lines:
times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)
if times != []:
current_times = map(convert_time, times)
elif line == '\n':
times_texts.append((current_times, current_text))
current_times, current_text = None, ""
elif current_times is not None:
current_text = current_text + line.replace("\n"," ")
print (times_texts)
from collections import Counter
whole_text = " ".join([text for (time, text) in times_texts])
all_words = re.findall("\w+", whole_text)
counter = Counter([w.lower() for w in all_words if len(w)>5])
print (counter.most_common(10))
cuts = [times for (times,text) in times_texts
if (re.findall("please",text) != [])]
from moviepy.editor import VideoFileClip, concatenate
video = VideoFileClip("Identity_2003.mp4")
def assemble_cuts(cuts, outputfile):
""" Concatenate cuts and generate a video file. """
final = concatenate([video.subclip(start, end)
for (start,end) in cuts])
final.to_videofile(outputfile)
assemble_cuts(cuts, "please.mp4")
But the assemble_cuts function is not working . I am using python3.x
it is giving me an error
Traceback (most recent call last):
File "<ipython-input-64-939ee3d73a4a>", line 47, in <module>
assemble_cuts(cuts, "please.mp4")
File "<ipython-input-64-939ee3d73a4a>", line 44, in assemble_cuts
for (start,end) in cuts])
File "<ipython-input-64-939ee3d73a4a>", line 43, in <listcomp>
final = concatenate([video.subclip(start, end)
File "<ipython-input-64-939ee3d73a4a>", line 6, in convert_time
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
TypeError: 'map' object is not subscriptable
Could you help me to solve this problem?
Fixed it.
def convert_time(timestring):
""" Converts a string into seconds """
nums = list(map(float, re.findall(r'\d+', timestring)))
return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
I am trying to implement a peer to peer file transfer protocol and i came across this code but when I ported it to python 3.6 I got this error "type error a bytes-like object is required not 'str'". Please can somebody help me out i am new to this.
server.py
! /usr/bin/python3.6
import subprocess
import socket
import sys
import os
import hashlib
HOST = 'localhost'
PORT = 8000
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Server Created')
except OSError as e:
print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
try:
s.bind((HOST, PORT))
except OSError as e:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print('Socket bind complete')
s.listen(1)
print('Server now listening')
while (1):
conn, addr = s.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
reqCommand = conn.recv(1024)
print('Client> %s' %(reqCommand))
string = reqCommand.split(' ')
if (reqCommand == 'quit'):
break
elif (reqCommand == 'lls'):
toSend=""
path = os.getcwd()
dirs=os.listdir(path)
for f in dirs:
toSend=toSend+f+' '
conn.send(toSend)
#print path
elif (string[1]== 'shortlist'):
path = os.getcwd()
command = 'find '+path+ ' -type f -newermt '+string[2]+' '+string[3]+ ' ! -newermt '+string[4]+' '+string[5]
var = commands.getstatusoutput(command)
var1 = var[1]
var=var1.split('\n')
rslt = ""
for i in var:
comm = "ls -l "+i+" | awk '{print $9, $5, $6, $7, $8}'"
tup=commands.getstatusoutput(comm)
tup1=tup[1]
str=tup1.split(' ')
str1=str[0]
str2=str1.split('/')
rslt=rslt+str2[-1]+' '+str[1]+' '+str[2]+' '+str[3]+' '+str[4]+'\n'
conn.send(rslt)
elif (string[1]=='longlist'):
path = os.getcwd()
var= commands.getstatusoutput("ls -l "+path+" | awk '{print $9, $5, $6, $7, $8}'")
var1 = ""
var1= var1+''+var[1]
conn.send(var1)
elif (string[0] == 'FileHash'):
if(string[1]== 'verify'):
BLOCKSIZE = 65536
hasher = hashlib.sha1()
with open(string[2], 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
conn.send(hasher.hexdigest())
print('Hash Successful')
elif (string[1] == 'checkall'):
BLOCKSIZE = 65536
hasher = hashlib.sha1()
path = os.getcwd()
dirs=os.listdir(path)
for f in dirs:
conn.send(f)
with open(f, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
conn.send(hasher.hexdigest())
print('Hash Successful')
else:
string = reqCommand.split(' ') #in case of 'put' and 'get' method
if(len(string) > 1):
reqFile = string[1]
if (string[0] == 'FileUpload'):
file_to_write = open(reqFile,'wb')
si = string[2:]
for p in si:
p = p + " "
print("User" + p)
file_to_write.write(p)
while True:
data = conn.recv(1024)
print("User" + data)
if not data:
break
file_to_write.write(data)
file_to_write.close()
print('Receive Successful')
elif (string[0] == 'FileDownload'):
with open(reqFile, 'rb') as file_to_send:
for data in file_to_send:
conn.sendall(data)
print('Send Successful')
conn.close()
s.close()
This is the error from the server.
Server Created
Socket bind complete
Server now listening
Connected with 127.0.0.1:37760
Client> b''
Traceback (most recent call last):
File "./server.py", line 36, in <module>
string = reqCommand.split(' ')
TypeError: a bytes-like object is required, not 'str'
This is the client side of my program but having the same problem.
client.py
#! /usr/bin/python3.6
import socket
import sys
import os
import hashlib
HOST = 'localhost' #server name goes in here
PORT = 8000
def put(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
string = commandName.split(' ')
inputFile = string[1]
with open(inputFile, 'rb') as file_to_send:
for data in file_to_send:
socket1.sendall(data)
print("Client users " + data)
socket1.send(data)
print('Upload Successful')
socket1.close()
return
def get(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName(data. 'utf-8'))
string = commandName.split(' ')
inputFile = string[1]
with open(inputFile, 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
if not data:
break
# print data
file_to_write.write(data)
file_to_write.close()
print('Download Successful')
socket1.close()
return
def FileHash(commandName):
string = commandName.split(' ')
if string[1] == 'verify':
verify(commandName)
elif string[1] == 'checkall':
checkall(commandName)
def verify(commandName):
socket1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
hashValServer=socket1.recv(1024)
string = commandName.split(' ')
BLOCKSIZE = 65536
hasher = hashlib.sha1()
with open(string[2], 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
hashValClient = hasher.hexdigest()
print('hashValServer= %s', (hashValServer))
print('hashValClient= %s', (hashValClient))
if hashValClient == hashValServer:
print('No updates')
else:
print('Update Available')
socket1.close()
return
def checkall(commandName):
socket1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ')
BLOCKSIZE = 65536
hasher = hashlib.sha1()
# f=socket1.recv(1024)
while True:
f=socket1.recv(1024)
with open(f, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
hashValClient = hasher.hexdigest()
hashValServer=socket1.recv(1024)
print ('Filename = %s', f)
print('hashValServer= %s', (hashValServer))
print('hashValClient= %s', (hashValClient))
if hashValClient == hashValServer:
print('No updates')
else:
print('Update Available')
if not f:
break
socket1.close()
return
def quit():
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
socket1.close()
return
def IndexGet(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
string = commandName.split(' ')
if string[1] == 'shortlist':
socket1.send(commandName)
strng=socket1.recv(1024)
strng=strng.split('\n')
for f in strng:
print(f)
elif (string[1]=='longlist'):
socket1.send(commandName)
path=socket1.recv(1024)
rslt=path.split('\n')
for f in rslt[1:]:
print(f)
socket1.close()
return
def serverList(commandName):
socket1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
fileStr=socket1.recv(1024)
fileList=fileStr.split(' ')
for f in fileList[:-1]:
print(f)
socket1.close()
return
msg = input('Enter your name: ')
while(1):
print("\n")
print("****************")
print('Instruction')
print('"FileUpload [filename]" to send the file the server ')
print('"FileDownload [filename]" to download the file from the server ')
print('"ls" to list all files in this directory')
print('"lls" to list all files in the server')
print('"IndexGet shortlist <starttimestamp> <endtimestamp>" to list the files modified in mentioned timestamp.')
print('"IndexGet longlist" similar to shortlist but with complete file listing')
print('"FileHash verify <filename>" checksum of the modification of the mentioned file.')
print('"quit" to exit')
print("\n")
sys.stdout.write ('%s> ' %msg)
inputCommand = sys.stdin.readline().strip()
if (inputCommand == 'quit'):
quit()
break
elif (inputCommand == 'ls'):
path = os.getcwd()
dirs = os.listdir(path)
for f in dirs:
print(f)
elif (inputCommand == 'lls'):
serverList('lls')
else:
string = inputCommand.split(' ', 1)
if string[0] == 'FileDownload':
get(inputCommand)
elif string[0] == 'FileUpload':
put(inputCommand)
elif string[0] =='IndexGet':
IndexGet(inputCommand)
elif string[0] == 'FileHash':
FileHash(inputCommand)
I expexted it to transfer the file without any error, Please i am new to this can anybody help me out.
This the error from the client
FileUpload closer.mp3
g> Traceback (most recent call last):
File "./client.py", line 193, in <module>
put(inputCommand)
File "./client.py", line 16, in put
socket1.send(commandName)
TypeError: a bytes-like object is required, not 'str'
You're trying to send a string even though a byte array is needed.
in 'socket1.send(commandName)' write socket1.send(commandName.encode('utf-8') instead
same thing serverside.
You should really rethink coding a cryptocurrency if you can't figure out the difference between bytes and strings. Start with an easier project.
When the following bit of code runs, most specifically the last 'else'condition, I get this error: OSError: [Errno 22] Invalid argument: 'My Name\n-Groups.txt'
What should I do so that '\n' isn't included in the file name as I would like it to just be 'My Name-Groups.txt'.
def add_child_to_group():
file = open("Children.txt", 'r') # open the Children.txt file
lineList = file.readlines()
lineList.sort()
file.close()
choice1 = choicebox('Choose a child to enter into a group.', 'Add child to a group. ', choices=lineList)
if choice1 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
file = open("Groups.txt", 'r')
lineList = [line.strip() for line in file]
choice2 = choicebox("Which group would you like to add the child to?", "Choose a group.",
choices=lineList)
file.close()
if choice2 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
if choice1 in open('%s.txt' % choice2).read():
child_already_in_group(choice1, choice2)
return
else:
file1 = open('%s.txt' % choice2, 'a')
file1.write(str(choice1))
print(str(choice1) + "was added to the " + str(choice2) + " group")
file1.close()
file2 = open('%s-Groups.txt' % choice1, 'a')
file2.write(str(choice2))
Something like this can do:
>>> st = 'My Name\n-Groups.txt'
>>> st.replace('\n','')
'My Name-Groups.txt'
>>>
So, in your code, you can make the following change:
file2 = open(('%s-Groups.txt' % choice1).replace('\n',''), 'a')