I'm using 'sys' module to get the filename as an argument in the command line while I'm running the script in cmd it is working as I want, but if I run this in PyCharm it raises an error Index Error: list index out of range. How to get rid of this error in PyCharm?
Here is the Code I'm trying to run:
import sys
def read_lines(file):
list_of_numbers = []
with open(file, mode='r') as read_file:
for number in read_file:
number = number.strip()
list_of_numbers.append(number)
return list_of_numbers
if __name__ == '__main__':
fun = read_lines(sys.argv[1])
print(fun)
While running the script directly from pycharm it raises following error:
Traceback (most recent call last):
File "D:\pythonProjects\test.py", line 10, in <module>
fun = read_lines(sys.argv[1])
IndexError: list index out of range
Presumably that's because you don't provide any arguments when running the script in PyCharm.
You can run the following script to print all the arguments:
import sys
if __name__ == '__main__':
print(sys.argv)
If you run it in the command line something like this
python3 test.py filename.txt
You should the output
['test.py', 'filename.txt']
(the first argument is the name of your script).
In PyCharm, you also have to specify filename.txt as a parameter.
Otherwise, you only get
['test.py']
which means that there is no element 1, hence the IndexError.
You can fix it by adding the filename.txt parameter to your run configuration in PyCharm.
Related
I have some input file in a directory and want to make a python script with 2 functions and run the script for all of the input files in the same directory.
the script that I made still does not work. there are 2 functions. the first one is the one which takes the input files and returns the output files. if I run this function on every single input file, it will work perfectly. so there is no problem with the function "convert".
the 2nd function in main function which is made for "argparse". the script has problem in this function.
import argparse
import pytools
def convert(infile, outfile):
x = pytools.split(infile)
x.coverage(bh=True, split=True)\
.saveas(outfile, type='bh')
print "done"
return
def main():
parser=argparse.ArgumentParser()
parser.add_argument("-b", "--infile", required=True)
parser.add_argument("-o", "--output", required=True)
args = parser.parse_args()
input = args.infile
output = convert(args.infile)
if __name__ == '__main__':
main()
my problem is that, I do not know if introducing the input files and call for output files is done in a correct way or not. in fact I think the problem of this script is in this part:
input = args.infile
output = convert(args.infile)
do you know how to fix the script?
this is the problem I get after running the script:
Traceback (most recent call last):
File "bam2bg.py", line 39, in <module>
main()
File "bam2bg.py", line 35, in main
input = args.infile
AttributeError: 'Namespace' object has no attribute 'infile'
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-r', action='store',dest='box',type=int,help='store')
print parser.parse_args()
when i try to run the above code o/p is
>
Namespace(box=None)
when i give the "-r" the error rises.
-r
Traceback (most recent call last):
File "", line 1, in
-r
NameError: name 'r' is not defined
how to fix this error!!!!!!!!!!!
Just run it by
Python filename -r some integer value
You would get your expected result
If u want the parameter to be optional use --r in .add_argument()
it expects int value so first try putting -r in quotes and then after a space pass an integer value it will work. say for instance,the code is stored in a file named q1.py you can run it as:
python q1.py '-r' 5
on running this it is expected to give
Namespace(box=5)
I recognize there are a decent amount of ValueError questions on here, but it seems none are specifically related to psychopy or my issue. I am coding an experiment from scratch on psychopy (no builder involved). Yesterday, my script was running totally fine. Today I tried running it without adding anything new or taking anything away and it's suddenly giving me this error:
File "/Users/vpam/Documents/fMRI_binding/VSTMbindingpaige.py", line 53, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
These are lines 52 and 53, apparently something in 53 (the last one) is making this happen, but I can't imagine what since it was working just fine yesterday. Anyone know why it's doing that? (I am running the oldest version of python in order to be able to include corrective audio feedback, but I have been running it on that with success):
from sys import argv
script, filename = argv
This is what I'm calling the filename (in the script it is above those other lines)
from sys import argv
script, filename = argv
from psychopy import gui
myDlg = gui.Dlg(title="Dr. S's experiment")
myDlg.addField('Subject ID','PJP')
ok_data = myDlg.show()
if myDlg.OK:
print(ok_data)
else:
print('user cancelled')
[sID]=myDlg.data
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
data_file = sID + '_VSTMbinding.txt'
f = open(data_file,'a') #name file here
f.write(sID)
print myDlg.data
It looks like you're using Python2. Python3 gives a more detailed information in it's error message. The problem is that argv only contains a single value and you're trying to unpack it into two variables. argv contains the command line variables -- if this was running yesterday "without any changes" as you suggest, it's because you were providing a filename as a command-line argument.
py2.py
#!/usr/bin/env python
from sys import argv
script, filename = argv
print("Script: {0}\nFilename: {1}".format(script, filename))
py3.py
#!/usr/bin/env python3
from sys import argv
script, filename = argv
print("Script: {0}\nFilename: {1}".format(script, filename))
Running py2.py:
$ charlie on laptop in ~
❯❯ ./py2.py
Traceback (most recent call last):
File "./py2.py", line 4, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
$ charlie on laptop in ~
❯❯ ./py2.py filename
Script: ./py2.py
Filename: filename
Running py3.py:
$ charlie on laptop in ~
❯❯ ./py3.py
Traceback (most recent call last):
File "./py3.py", line 4, in <module>
script, filename = argv
ValueError: not enough values to unpack (expected 2, got 1)
$ charlie on laptop in ~
❯❯ ./py3.py filename
Script: ./py3.py
Filename: filename
When using python's sh module (not a part of stdlib), I can call a program in my path as a function and run it in the background:
from sh import sleep
# doesn't block
p = sleep(3, _bg=True)
print("prints immediately!")
p.wait()
print("...and 3 seconds later")
And I can use sh's Command wrapper and pass in the absolute path of an executable (helpful if the executable isn't in my path or has characters such as .):
import sh
run = sh.Command("/home/amoffat/run.sh")
run()
But trying to run the wrapped executable in the background, as follows:
import sh
run = sh.Command("/home/amoffat/run.sh", _bg=True)
run()
Fails with a traceback error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument '_bg'
How can I run an executable wrapped by sh.Command in the background? Looking for an elegant solution.
EDIT:
I used the python interpreter for testing passing _bg to the command (not the wrapper), which I now realize is a bad way to test for blocking and non-blocking processes:
>>> import sh
>>> hello = sh.Command("./hello.py")
>>> hello(_bg=True) # 5 second delay before the following prints and prompt is returned
HI
HI
HI
HI
HI
With hello.py being as follows:
#!/usr/bin/python
import time
for i in xrange(5):
time.sleep(1)
print "HI"
import sh
run = sh.Command("/home/amoffat/run.sh", _bg=True) # this isn't your command,
# so _bg does not apply
run()
Instead, do
import sh
run = sh.Command("/home/amoffat/run.sh")
run(_bg=True)
(BTW, the subprocess module provides a much less magical way to do such things.)
Running Python 2.5 on Windows XP SP2.
When I run a Python script that calls a user-defined module called Zipper.py (basically a wrapper for a zipfile) using a Windows scheduledTask I get this exception:
Traceback (most recent call last):
File "C:\PythonScripts\ZipAndSendEOD-Reports.py", line 78, in main
Zipper.main([report],f, debug=True) #[:-4] + "_" + str(x) + ".zip")
TypeError: main() got an unexpected keyword argument 'debug'
The odd thing is that if I simply open the file in IDLE and hit 'F5', it runs flawlessly.
I'm sure I left out some pertinent information, please let me know what you need.
Zipper.py looks like this:
import zipfile
def main(archive_list=[],zfilename='default.zip', debug=False):
if debug: print 'file to zip', zfilename
zout = zipfile.ZipFile(zfilename, "w", zipfile.ZIP_DEFLATED)
for fname in archive_list:
if debug: print "writing: ", fname
zout.write(fname)
zout.close()
if __name__ == '__main__':
main()
EDIT:
I added the following two lines of code to the calling function, and it now works.
f = open(logFile, 'a')
f.write(Zipper.__file__)
Can you explain THAT to me?
As Paul said, you're probably running a different version of Zipper.py - I would print out Zipper.__file__ and then if you need to debug, print out sys.path to see why it's finding a different file.