PYTHON - TRY: ARGV STILL ERRORS OUT - python-3.x

Just trying to handle some IndexError while using sys. Searched a lot on how to do it, and I've come to a final "solution", but I don't know why it's not working.
Actual code
#!/usr/bin/python3
import sys
t = sys.argv[1]
u = sys.argv[2]
try:
t = sys.argv[1]
except IndexError:
print("no arg 1")
try:
u = sys.argv[2]
except IndexError:
print("no arg 2")
Output
Traceback (most recent call last):
File "/home/try.py", line 9, in <module>
t = sys.argv[1]
IndexError: list index out of range
I don't know why it errors out, since I have set previously the sys.argv[1] inside the try block
Could anyone help me out on this?
EDIT:
I was able to find a way around for this, which is, a separate script for different stuff.

The issue comes from the t and u definitions above the two try blocks. Get rid of those and keep your try blocks and you should be good.

In addition to the spurious statements at the start (i.e. outside of the try statement), I think you are misunderstanding how array subscripting works in Python.
Python arrays start from subscript 0 (not 1). For an array with 2 elements, their subscripts are 0 and 1. So your code should be:
import sys
try:
t = sys.argv[0] # <<<
except IndexError:
print("no arg 1")
try:
u = sys.argv[1] # <<<
except IndexError:
print("no arg 2")
Searched a lot on how to do it ...
Can I point out that this is NOT a good way to learn to program ... or to find the bugs in your code. You should not be searching for "solutions". You should be reading your code, and looking at the evidence and trying to figure out what you have done wrong.
For example, the version of the code in your question actually produces this output:
$ ./test.py
Traceback (most recent call last):
File "./test.py", line 5, in <module>
t = sys.argv[1]
IndexError: list index out of range
It says that the error is on line 5. Then you look at the code and see that line 5 is NOT in the try: statement.
Secondly, you should be consulting reliable resources on Python; e.g. the official documentation, a textbook, or a decent tutorial. They will explain clearly how array subscripting works, for example.

Related

How to randomly copy the contents of a text document to my clipboard

This is my original question
The following script copies the text in /home/my_files/document1.txt to my clipboard.
import pyperclip
path = '/home/my_files/document1.txt'
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Let's say /home/my_files/ contains the following five documents:
/home/my_files/document1.txt
/home/my_files/document2.txt
/home/my_files/document3.txt
/home/my_files/image1.jpg
/home/my_files/image2.png
I would like to create a script to randomly copy the contents of one of the three text documents in /home/my_files/ to my clipboard.
Of course the following script does not work but it shows some of the modules I've been experimenting with.
import glob,random,pyperclip
pattern = "*.txt"
path = random.choice((glob.glob(pattern))("/home/my_files/"))
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Do you have any relevant suggestions for me?
I added the subsequent content to my original question above
When I tried the following solution which #Jacob Lee created...
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())
I received the following error message...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
Someone else suggested the following script to me...
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
But that script doesn't work either. I received the following error when I ran that script...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
I am confused.
The following successfully copies the entire contents of a random text file in /home/my_files/ to my clipboard
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Thanks to #Asocia
Thanks to #Asocia for insisting that the script above works correctly. I don't know what I had been doing wrong, but I must have been doing something wrong when I indicated the script above did not work properly.
You're code raises a TypeError: 'list' object is not callable exception when you try to assign path, in this line:
path = random.choice((glob.glob(pattern))("/home/my_files"))
glob.glob() returns a list (possibly empty). (Also, you put the glob.glob() call inside redundant parentheses.) Then, you try to call glob.glob()("/home/my_files/") (in essence, [...](), raising the TypeError exception.
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files/*.txt")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())

How do I fix this EOF error on python 3 version

I am working on a very basic problem on Hackerrank.
Input format:
First line contains integer N.
Second line contains string S.
Output format:
First line should contain N x 2.
Second line should contain the same string S.
sample test case
5
helloworld
my code is as: (on PYTHON 3)
n=int(input())
s=input()
print(2*n)
print(s)
I am getting error:
Execution failed.
EOFError : EOF when reading a line
Stack Trace:
Traceback (most recent call last):
File "/tmp/143981299/user_code.py", line 1, in <module>
N = int(input())
EOFError: EOF when reading a line
I tried this method to take input many times and this is the first time I am having this error. Can anyone please explain why?
use a try/except block to handle the error
while True:
try:
n=int(input())
s=input()
print(2*n)
print(s)
except:
break

Learn Python the Hard Way -- ex17.py under python-3 environment

I try to learn this book under python-3 environment but it pops out an error when I try to run it. Is there anywhere to fix this?
Once I deleted
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
The code ran perfectly. So I think it should be the syntax problem between python 2 and python 3
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print("Copying from %s to %s" % (from_file,to_file))
# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()
print("The input file is %d bytes long" % len(indata))
print("Does the output file exist? %r" % exists(to_file))
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
out_file = open(to_file, 'w')
out_file.write(indata)
print("Alright, all done")
out_file.close()
in_file.close()
When I try to run it, it should stops at input() and wait me hit the return key to continue. But in reality, the code stopped and an error called
"Traceback (most recent call last):
File "ex17.2.py", line 18, in <module> g
input("")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
popped out.
Yes you are correct!! The error you are getting is due to python version change. This code works perfectly fine in python 3.x but fails in python version under 3.x.
Hope this helps.

Taking input while accounting for both Python 2.x and 3.x

Since Python 2's raw_input was changed to just input for Python 3, I was wondering if there was a way to take input while accounting for both Python 2 and 3. I'm trying to write a script for both versions, and this input part is the only thing that's not working well.
I tried running just input with Py2, and this happens:
>>> a = input('Input: ')
inp: test
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
a = input('Input: ')
File "<string>", line 1, in <module>
NameError: name 'test' is not defined
I saw a workaround to quote the input:
>>> a = input('Input: ')
inp: "testing test"
a
'testing test'
Is there a way to concatenate the quote to the beginning and end of the input? '"' + input('input: ') + '"' isn't working
Probably not a good practice, but you can use a try block to test whether the raw_input() is being recognized (thus telling you whether you're on Python 2.x or Python 3.x):
try:
a = raw_input('input: ')
except NameError:
a = input('input: ')
I would use raw_input() to test because it's not accepted by Python 3.x and is what you expect to use in Python 2.x, so the input() will not trigger in Python 2.x.
I'm not an expert so I'm sure there are better suggestions.
#Chris_Rands' suggested dupe thread has a more elegant solution by binding input = raw_input so if you have multiple input(), you only need to try once.
This works for both Python 2 and 3.
from builtins import input
input("Type something safe please: ")

EOFError in pickle.load and file not found error

elif(ch==2):
fh=open("emp1.txt","rb+")
fo=open("temp.txt","wb+")
ecode=input("Enter the Ecode :")
rec=(" ")
try:
while True:
emp1= pickle.load(fh)
if (emp1.ecode!=ecode):
pickle.dump(emp1,fh)
except(EOFError):
fh.close()
fo.close()
os.remove("empl.txt")
os.rename("temp.txt","emp1.txt")
print("")
running the following code gives me this error:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 78,
in
emp1= pickle.load(fh) EOFError
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 85,
in
os.remove("empl.txt") FileNotFoundError: [WinError 2] The system cannot find the file specified: 'empl.txt'
What should i do now??
You should fix your path. In the first case, you write "emp1.txt"; and in the second, you write "empl.txt". If you look carefully, you should notice that there is a difference in those two strings.
Hint: '1' != 'l'
Your code could probably be refactored as well. While it is not possible for others to test your code since it is very incomplete, the following should work in its place. You will still need to verify it works.
elif ch == 2:
with open('emp1.txt', 'rb+') as fh, open('temp.txt', 'wb+') as fo:
ecode = input('Enter the Ecode: ')
while True:
try:
item = pickle.load(fh)
except EOFError:
break
else:
if item.ecode != ecode:
pickle.dump(item, fo)
os.remove(fh.name)
os.rename(fo.name, fh.name)
print()
I would use shelve, its much easier to use and it doesn't come up with to many errors in my experience. shelve is built on pickle but it just simplify it.
here is a short tutorial
http://python.wikia.com/wiki/Shelve

Resources