I am trying to make a simple Python tool for copying all the contents from drive x to drive y, where it asks the user what the source and destination drives are.
Works great when I run it from inside Visual Studio, but when I try to run it via the command line (python.exe pythonapplication1.py), I get this error in the output:
What is your source drive letter?f
Traceback (most recent call last):
File "pythonapplication1.py", line 7, in <module>
inputSrc = input("What is your source drive letter?")
File "<string>", line 1, in <module>
NameError: name 'f' is not defined
Here is my code for this program:
import os
import sys
inputSrc ="x"
inputDest = "y"
inputSrc = input("What is your source drive
letter?")
inputDest = input("What is the destination drive
letter?")
src = inputSrc + ": "
dest = inputDest + ": "
copyCommand = "xcopy " + src + dest + "/s"
os.system(copyCommand)
loopCheck = "no"
while loopCheck == "no":
questionTest = input("Want to make another copy? y/n ")
if questionTest == "y":
input("Press any key once you put in the new blank drive.")
os.system(copyCommand)
if questionTest == "n":
loopCheck = "yes"
You should use raw_input("question...") instead of input("question...") in python2. This is because input will take the users input and execute it. This is why the interpreter complains about not knowing f.
You can use raw_input() instead of input()
i.e.
inputSrc = raw_input("What is your source drive
letter?")
inputDest = raw_input("What is the destination drive
letter?")
will work.
Related
I am following the tutorial of protobuf using Python (there isn't one for JavaScript). It doesn't work... and I think it might be outdated as proto2 and as a Python 2 program. How to make it work?
So I started with creating a file address.proto:
syntax = "proto2";
package tutorial;
message Person {
optional string name = 1;
optional int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
optional string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phones = 4;
}
message AddressBook {
repeated Person people = 1;
}
And then I installed protoc on the Mac
And then I created two folders In and Out, and moved address.proto into In, and run:
protoc -I=In --python_out=Out In/address.proto
and then there is a file created: Out/address_pb2.py, and I went to Out, and added the file run.py:
#! /usr/bin/python
import addressbook_pb2
import sys
# This function fills in a Person message based on user input.
def PromptForAddress(person):
person.id = int(raw_input("Enter person ID number: "))
person.name = raw_input("Enter name: ")
email = raw_input("Enter email address (blank for none): ")
if email != "":
person.email = email
while True:
number = raw_input("Enter a phone number (or leave blank to finish): ")
if number == "":
break
phone_number = person.phones.add()
phone_number.number = number
type = raw_input("Is this a mobile, home, or work phone? ")
if type == "mobile":
phone_number.type = addressbook_pb2.Person.PhoneType.MOBILE
elif type == "home":
phone_number.type = addressbook_pb2.Person.PhoneType.HOME
elif type == "work":
phone_number.type = addressbook_pb2.Person.PhoneType.WORK
else:
print "Unknown phone type; leaving as default value."
# Main procedure: Reads the entire address book from a file,
# adds one person based on user input, then writes it back out to the same
# file.
if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
# Read the existing address book.
try:
f = open(sys.argv[1], "rb")
address_book.ParseFromString(f.read())
f.close()
except IOError:
print sys.argv[1] + ": Could not open file. Creating a new one."
# Add an address.
PromptForAddress(address_book.people.add())
# Write the new address book back to disk.
f = open(sys.argv[1], "wb")
f.write(address_book.SerializeToString())
f.close()
and then I installed and ran:
pip3 install protobuf --user
pip3 install google --user
pip3 install google-cloud --user
python3 run.py addr.dat
and it looks like I have to convert the code in run.py from print 123 to print(123) because it is Python3, not Python2. And it gave:
Traceback (most recent call last):
File "run.py", line 40, in <module>
address_book = addressbook_pb2.AddressBook()
NameError: name 'addressbook_pb2' is not defined
I also copied the file addressbook_pb2.py to foo.py, and then use import foo instead, and it gave:
Traceback (most recent call last):
File "run.py", line 3, in <module>
import foo
File "/Users/peter/code/TryProtobuf_Unzipped/TryIt/Out/foo.py", line 34, in <module>
_descriptor.EnumValueDescriptor(
File "/Users/peter/Library/Python/3.8/lib/python/site-packages/google/protobuf/descriptor.py", line 732, in __new__
_message.Message._CheckCalledFromGeneratedFile()
TypeError: Descriptors should not be created directly, but only retrieved from their parent.
How can it be made to work?
Your address.proto declares the tutorial package. I think you can access it via address_book = tutorial.addressbook_pb2.AddressBook()
As for why it broke after renaming the file to foo.py, I have no idea.
I'm trying to code a password generator but it's not working and I can't understand the error.
import random
import string
lw = list(string.ascii_lowercase)
uw = list(string.ascii_uppercase)
ns = list(string.digits)
password = ""
def addLW():
f = randrange(1, len(lw))
password = password + lw[f]
def addUW():
f = randrange(1, len(lw))
password = password + uw[f]
def addN():
f = randrange(1, len(lw))
password = password + ns[f]
funcs = [addLW, addUW, addN]
maxx = input("Password generator.\nMax: ")
if maxx.isdigit():
maxx = int(maxx)
for i in range(maxx):
func = random.choice(funcs)
func()
print(f"Password: {password}")
else:
print("Error")
Full error:
Traceback (most recent call last):
File "Password Generator.py", line 29, in <module>
func()
File "Password Generator.py", line 14, in addUW
f = randrange(1, len(lw))
NameError: name 'randrange' is not defined
I don't understand because I've already imported 'random'...
import random
You've imported random. That means your global namespace now contains the binding to the random namespace. It does not contain randrange() or anything else within that namespace, so you need to explicitly use random.randrange() if you want it to find that method.
You can bring randrange itself in to the global namespace with:
from random import randrange
but that suffers from a few issues:
that only gives you randrange(), not any other stuff from random;
it will quickly pollute your global namespace with names if you need other things; and
it will get tedious if you want to import a large number of things (unless you import *, but see the previous bullet point about polluting the global namespace).
I'm making a little script to run commands to allow user interact with slave. My user is Administrator but my script report me that access is denied. I tried on other path with other process but nothing's work. I'm an apprentice so i'm learning and i don't really understand where is my mistake ^^""
here's my script :
def CallDeadlineCommand(arguments, background=True, readStdout=True):
deadlineCommand = GetDeadlineCommand()
startupinfo = None
creationflags = 0
if os.name == 'nt':
if background:
# Python 2.6 has subprocess.STARTF_USESHOWWINDOW, and Python 2.7 has subprocess._subprocess.STARTF_USESHOWWINDOW, so check for both.
if hasattr(subprocess, '_subprocess') and hasattr(subprocess._subprocess, 'STARTF_USESHOWWINDOW'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
elif hasattr(subprocess, 'STARTF_USESHOWWINDOW'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
else:
# still show top-level windows, but don't show a console window
CREATE_NO_WINDOW = 0x08000000 # MSDN process creation flag
creationflags = CREATE_NO_WINDOW
arguments.insert(0, deadlineCommand)
stdoutPipe = None
if readStdout:
stdoutPipe = subprocess.PIPE
# Specifying PIPE for all handles to workaround a Python bug on Windows. The unused handles are then closed immediatley afterwards.
proc = subprocess.Popen(arguments, stdin=subprocess.PIPE, stdout=stdoutPipe, stderr=subprocess.PIPE,
startupinfo= startupinfo, creationflags=creationflags)
proc.stdin.close()
proc.stderr.close()
output = ""
if readStdout:
output = proc.stdout.read()
return output
My command who call the function :
CallDeadlineCommand([" RemoteControl ", str(computer_name()), " ForceStopSlave"])
and it return me this complete error :
Traceback (most recent call last):
File "C:/Users/francois.CIRCUS/PycharmProjects/DeadlineMiniMonitor/mini_uimw.py", line 455, in change_value
self.kill_deadlineslave()
File "C:/Users/francois.CIRCUS/PycharmProjects/DeadlineMiniMonitor/mini_uimw.py", line 538, in kill_deadlineslave
CallDeadlineCommand([" RemoteControl ", str(computer_name()), " ForceStopSlave"])
File "C:/Users/francois.CIRCUS/PycharmProjects/DeadlineMiniMonitor/mini_uimw.py", line 680, in CallDeadlineCommand
startupinfo=startupinfo, creationflags=creationflags)
File "C:\Python27\Lib\subprocess.py", line 394, in __init__
errread, errwrite)
File "C:\Python27\Lib\subprocess.py", line 644, in _execute_child
startupinfo)
WindowsError: [Error 5] Access is denied
Thanks, best,
Pixi
Recently I wrote a multiprocess code in Python 3.4 to download some images, it's working blazingly fast at first, then I get the following error and cannot start the program anymore.
Traceback (most recent call last):
File "multiprocessing_d.py", line 23, in <module>
main()
File "multiprocessing_d.py", line 16, in main
p.map(download, lines)
File "/usr/local/lib/python3.4/multiprocessing/pool.py", line 260, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "/usr/local/lib/python3.4/multiprocessing/pool.py", line 608, in get
raise self._value
multiprocessing.pool.MaybeEncodingError: Error sending result: '<multiprocessing.pool.ExceptionWithTraceback object at 0x7f1e047f32e8>'. Reason: 'TypeError("cannot serialize '_io.BufferedReader' object",)'
My code is as following
download_helper.py
import sys
import os
from pathlib import Path
url_prefix = r"Some prefix"
def setup_download_dir(dictionary):
download_dir = Path(dictionary)
if not download_dir.exists():
download_dir.mkdir()
return dictionary
def download_link(dictionary, line):
from urllib.request import urlretrieve
itemid = line.split()[0].decode()
link = line.split()[1].decode()
if (link.startswith("http")):
image_url = link
else:
image_url = url_prefix + link
if os.path.isfile(dictionary + "/" + itemid + ".jpg"):
#print("Already have " + itemid + ".jpg")
pass
else:
urlretrieve(image_url, dictionary + "/" + itemid + ".jpg")
multiprocessing_d.py
from functools import partial
from multiprocessing.pool import Pool
import sys
from time import time
from download_helper import setup_download_dir, download_link
def main():
file_path = sys.argv[1]
dic_path = sys.argv[2]
download_dir = setup_download_dir(dic_path)
download = partial(download_link, download_dir)
with open(file_path, 'rb') as f:
lines = f.readlines()
ts = time()
p = Pool(processes=16, maxtasksperchild=1)
p.map(download, lines)
p.close()
p.join()
print('Took {}s'.format(time() - ts))
f.close()
if __name__ == "__main__":
main()
I've tried to search online but didn't find much information useful. My suspect is that there might be some exception raised in urlretrieve, but I don't know how to debug it. Any comments or suggestions would be appreciated!!
James
How can I make Python loop through a file and convert the hex to ascii? The problem is that when Python loops through the file it sees \n and does not parse the file.
import binascii
fo = open('test.doc', 'r')
print fo.readlines()
dataFormatHex = binascii.a2b_hex ("%s" %fo)
output = ""
for char in dataFormatHex:
if char in string.printable: output += char
else: output += "."
print "\n" + output
The error trace is:
Traceback (most recent call last):
File "C:\Python27\hex2ascii-looper.py", line 7, in <module>
dataFormatHex = binascii.a2b_hex ("%s" %fo)
TypeError: Non-hexadecimal digit found
Here is what is in the test.doc:
140000003700000027000000260000006D0000008E000000040000002E000000000000001D00000003000000410000004D0000005800000094000000880000005E0000004F00000040000000360000007B000000660000005A00000042000000300000002F0000004300000048000000050000000C0000004900000044000000220000002D000000180000003800000011000000010000001500000009000000640000008100000020000000700000006C00000087000000650000000F000000610000005D0000001F000000210000001900000079000000690000008A0000008D0000002A0000008C00000073000000330000003B000000680000006F000000800000000E000000020000004A0000005900000039000000740000001C00000012000000060000001E000000830000006B0000006A000000750000000A0000007A00000023000000550000007E000000340000001B0000001700000084000000520000007700000092000000470000009300000076000000710000004600000060000000720000002B000000530000001A000000900000007D00000016000000670000008B00000063000000450000002C00000035000000070000005B00000050000000910000002900000086000000310000003A0000000D0000007F000000560000002400000054000000890000006E00000085000000950000008F0000004C0000007800000062000000570000003D0000000B00000010000000130000002500000032000000820000004E0000005C0000003F000000080000004B000000280000005F0000003C000000510000003E000000FFFFFFFF
310032002D00310038002D00310034005F004D0065007800690063006F0020006D0061006300680069006E006500730020006F007500740020006F006600200064006100740065002D006E00650077002E0078006C00730078000000D00032000000000000000000000031322D31382D31345F4D657869636F206D616368696E6573206F7574206F6620646174652D6E65772E786C73782E6C6E6B00900008000400EFBE00000000000000002A00000000000000000000000000000000000000000000000000310032002D00310038002D00310034005F004D0065007800690063006F0020006D0061006300680069006E006500730020006F007500740020006F006600200064006100740065002D006E00650077002E0078006C00730078002E006C006E006B00000040000000
6300620074006E005F0070007900740068006F006E005F003000350020002D002000530074006100740065006D0065006E00740073002C00200044006F00630075006D0065006E0074006100740069006F006E002C00200061006E0064002000480065006C0070002E0066006C0076000000F2003200000000000000000000006362746E5F707974686F6E5F3035202D2053746174656D656E74732C20446F63756D656E746174696F6E2C20616E642048656C702E666C762E6C6E6B0000A60008000400EFBE00000000000000002A000000000000000000000000000000000000000000000000006300620074006E005F0070007900740068006F006E005F003000350020002D002000530074006100740065006D0065006E00740073002C00200044006F00630075006D0065006E0074006100740069006F006E002C00200061006E0064002000480065006C0070002E0066006C0076002E006C006E006B0000004C000000
Just use .strip() on your string, it will remove the trailing \n.
import binascii
f = open(yourFile)
for line in f.readlines():
print(binascii.a2b_hex("%s" % (line.strip()))
f.close()