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)
Related
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.
I wrote the following code, which results in an error and I don't know how to fix it to work.
The code is:
# Name: ClipGDBtoNewGDB.py
# Description: Take an input GDB, create a list, iterate through each
feature class, clipping it and writing it to a new GDB.
# Author: tuilbox
# Import system modules
import arcpy, os
from arcpy import env
# Set workspace
env.workspace = arcpy.GetParameterAsText(0)
arcpy.env.overwriteOutput=True
# Set local variables
fclist = arcpy.ListFeatureClasses()
clip_features = arcpy.GetParameterAsText(1)
output_directory=arcpy.GetParameterAsText(2)
xy_tolerance = ""
outgdb=os.path.join(output_directory, arcpy.GetParameterAsText(3))
if not arcpy.Exists(outgdb):
arcpy.CreateFileGDB_management(output_directory,
arcpy.GetParameterAsText(3))
# Execute Clip within for loop
for fc in fclist:
arcpy.Clip_analysis(fc, clip_features, os.path.join(outgdb, fc))
The error is: Traceback (most recent call last):
File "F:/GIS_Joseph/Lab10_Joseph/ClipGDBtoNewGDB.py", line 17, in <module>
arcpy.CreateFileGDB_management(output_directory, arcpy.GetParameterAsText(3))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 18878, in CreateFileGDB
raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000735: File GDB Location: Value is required
ERROR 000735: File GDB Name: Value is required
Failed to execute (CreateFileGDB).
Any help would be appreciated. Thank you.
With this type of question it would be helpful to let us know what parameters you are passing into your script. Have you passed a valid parameter in position 3? Use arcpy.AddMessage to double check what value you are attempting to pass to arcpy.CreateFileGDB_management.
I have a fully working programme that I wish to run. It executes on my friend's laptop, but not mine, (I've saved it to my documents folder) the following is the program:
def DigitCount(n):
#how many decimal digits in integer 'n'
if n<0:
n=-n
digitCount=1
powerOfTen=10
while powerOfTen<=n:
digitCount+=1
powerOfTen*=10
return digitCount
But I keep getting the following error:
>>> DigitCount(100)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
DigitCount(100)
NameError: name 'DigitCount' is not defined
Wait, are you saying you do the following from the command line?
$ python DigitCount.py
$ python
>>> DigitCount(100)
That won't work. You have to do this:
$ python
>>> import DigitCount
>>> DigitCount.DigitCount(100)
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
I'm trying to pass an array from bash to python using the old getenv method however I keep getting this error:
./crcFiles.sh: line 7: export: `0021': not a valid identifier
Traceback (most recent call last):
File "/shares/web/vm3618/optiload/prog/legalLitres.py", line 30, in <module>
for i in mdcArray.split(' '):
AttributeError: 'NoneType' object has no attribute 'split'
could someone please explain why the $mdcNo isn't passing from bash to python successfully?
Code .sh:
#!/bin/bash
mdcNo=('0021' '0022' '0036' '0055' '0057' '0059' '0061' '0062' '0063' '0065' '0066' '0086' '0095' '0098' '0106' '0110' '0113' '0114' '0115' '0121' '0126' '0128' '0135' '0141' '0143' '0153' '0155' '0158')
localDIR=/shares/web/vm3618/optiload/prog
export mdcNo
$localDIR/legalLitres.py
for i in "${mdcNo[#]}"
do
echo $i
cp $localDIR/MDC$i/*/QqTrkRec.txt $localDIR/crccalc/.
cd $localDIR/crccalc
./crccalc.py QqTrkRec.txt
cp $localDIR/crccalc/QqTrkRec.txt $localDIR/MDC$i/.
done
code .py:
#!/usr/bin/python
import glob
import os
mdcArray = os.getenv('mdcNo')
#Legal Litres that hex and decimal
legalLitresHex = "47E0"
legalLitresTxt = '18,400'
# file name and Legal Litres header
legalHeader = ":00F0:"
hexFile = "QqTrkRec.txt"
# insert comment to explain change
comment = "#\n# 2015 Nov 20: Legal Litres changed to 18,400\n#\n"
commentFlag0 = "# SetDATA"
commentFlag1 = "# SetDATA"
try:
for i in mdcArray.split(' '):
line = ""
Qqfile = glob.glob("/shares/web/vm3618/optiload/prog/MDC"+i+"/*/"+hexFile)
outFile = Qqfile[0]+".new"
print i
If you want to pass a shell array to the Python script, your best bet is to do so as command line arguments. If you run the Python script like this:
python code.py "${mdcNo[#]}"
... then the Python code can just loop over sys.argv, which is always a list. (Specifically, the passed-in array will be the slice sys.argv[1:], since sys.argv[0] is always set to the name of the script itself.)
You were attempting to pass it in through the environment; the problem there is that the environment is a one-dimensional array of strings, with no support for arrays. If the command line is not an option and you have no choice but to use the environment, you'll have to set the environment variable to a string with some delimiter between elements, and split it inside the Python code. The bash for that case would look something like this:
export mdcList='0021,0022,0036,0055,0057,0059,0061,0062,0063,0065,0066,0086,0095,0098,0106,0110,0113,0114,0115,0121,0126,0128,0135,0141,0143,0153,0155,0158'
Or if you already have a bash array, you can build the strong from it:
export mdcList=${mdcNo[0]}
for i in "${mdcNo[#]:1}"; do
mdcList+=,$i
done
Either way, the Python script can recover the array as a list like this:
mdc_no = os.getenv('mdcList').split(',')
If your array elements aren't just numbers, you can replace the comma with something less likely to show up inside an element value; the traditional choice would be the ASCII Unit Separator (U+001F, $'\x1f' in Bash, '\x1f' in Python).
I think Mark Reed already gave you a very good explanation and solution.
Nevertheless, have you considered using python's argparse?
#!/usr/bin/env python
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('stuff', nargs='+')
args = parser.parse_args()
print args.stuff
if __name__ == '__main__':
main()
Use:
$ mdcNo=('0021' '0022' '0036' '0055' '0057' '0059' '0061' '0062' '0063' '0065' '0066' '0086' '0095' '0098' '0106' '0110' '0113' '0114' '0115' '0121' '0126' '0128' '0135' '0141' '0143' '0153' '0155' '0158')
$ python argp.py "${mdcNo[#]}"
['0021', '0022', '0036', '0055', '0057', '0059', '0061', '0062', '0063', '0065', '0066', '0086', '0095', '0098', '0106', '0110', '0113', '0114', '0115', '0121', '0126', '0128', '0135', '0141', '0143', '0153', '0155', '0158']