Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i am very new to python.
i would like to write a script where if i didn't pass any value to an argument, it should ask value for that argument. if passed, it should pick that value and continue.passing these values are from command line.
i tried below code and python is throwing error saying variable is not initialized.
if (fileName == None)
fileName == "C:\\filename"
print(fileName)
command line call for executing the script:- script.py "C:\filename"
Stack trace :-
if(NO_ERROR == None)
^
SyntaxError: invalid syntax
You are missing a colon at the end of the if statement
if (fileName == None):
fileName = "C:\\filename"
print(fileName)
sys module provides lots of options to play with command line arguments.
below example might be helpful to you.
import sys
#storing the argument in string
st=" ".join(sys.argv)
#splitting the list to get the file name and storing it in list
var=st.split('=')
if len(sys.argv)<2:
print "Enter Argument\n"
else:
print 'Argument found'
print var[1]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
Consider the following code:
code = input()
eval(code)
If I run it and type
> print(10)
It will get executed and print "10"
My question is when the code needs an indent, such as:
> for i in range(10):
> print(i)
How can I receive this code with input() (notice that I have to keep the indent) so that I can use eval() to run it?
If i understand correctly you want to be able to get python code using input() with tabs included.
the post
How to read multiple lines of raw input? tells us that we can get multiline input with
code = '\n'.join(iter(input, ''))
But after trying that myself I noticed that exec(code) didn't work because tabs were omitted from the input.
So here's a function that reads character directly and stops when it reads a given string
(here it's 2 newlines so you have to press ENTER twice to stop)
import sys
def input_until(sentinel):
text = ""
while not text.endswith(sentinel):
text += sys.stdin.read(1) # read 1 character from stdin
# remove the stop string from the result
return text[:-len(sentinel)]
code = input_until("\n\n")
exec(code)
I've tested it on https://replit.com/languages/python3 and it seems to work !
What's your use case here?
If you want to run the string in eval(), do you consider this?
new_string_name = "for i in range(10):\n eval(a)"
or
new_string_name = " eval()"
But if you don't want to follow the indentation rules (4 characters, no tabs), you can use
new_string_name = "for i in range(10):\n\teval(a)"
or
new_string_name = "\teval(a)"
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
hi I have the following block of test code (test lab).
#<snip>
client_mac = 'f8:cf:c5:a4:a2:84'
#<snip>
# issue a command1
my_command_output1 = my_wlc_session.sendcommand("grep include f8:cf:c5:a4:a2:84 \"show client summary\" \n")
# print the output
print(my_command_output1)
#
# issue a command2
my_command_output2 = my_wlc_session.sendcommand("grep include %s \"show client summary\" \n") % client_mac
# print the output
print(my_command_output2)
#<snip>
Command1 works as expected.
But command2 is the issue. I want some way of passing the client_mac to the command, but the code I am using results in this;
TypeError: not enough arguments for format string
I think this is something to do with the /n , but I need a 2nd new-line after the command for it to be executed.
Is there a better way of passing the client_mac? Or am I doing something else wrong.
Your closing parenthesis seems to be in the way. Try:
my_command_output2 = my_wlc_session.sendcommand("grep include %s \"show client summary\" \n" % client_mac)
While you're at it, the new .format() is becoming more popular, and makes bugs like this a little easier to notice. That'd look like:
my_command_output2 = my_wlc_session.sendcommand("grep include {} \"show client summary\" \n".format(client_mac))
Your code problem is here:
("grep include %s \"show client summary\" \n") % client_mac
Your % client_mac is supposed to be inside the parenthesis with the string you are formatting it into ("grep include %s \"show client summary\" \n").
The error means you specified a format string (%s) but did not include the variable to insert (because it was outside the parenthesis, and therefore, not part of the expression).
Re-reading your question, I believe the source of your confusion is that you thought you were passing multiple arguments to your function. You are actually just passing a single argument, a string (which you are formatting to include the client_mac).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I tried to solve the following problem by creating a new file, then tried each one of these functions to get the file extension but all i got was errors.
What am I doing wrong?
"Examine the following three functions that take as argument a file name and return the extension of that file. For instance, if the file name is 'myfile.tar.gz' the returned value of the function should be 'gz'. If the file name has no extention, i.e. when the file name is just 'myfile', the function should return an empty string."
def get_extension1(filename):
return(filename.split(".")[-1])
def get_extension2(filename):
import os.path
return(os.path.splitext(filename)[1])
def get_extension3(filename):
return filename[filename.rfind('.'):][1:]**
Which of the these functions are doing exactly what they are supposed to do according to the description above?
a) get_extension1 and get_extension3
b) get_extension3 only
c) get_extension2 and get_extension3
d) All of them
get_extension1(filename) will return the file name if filename does not contain .
get_extension3(filename) will raise an error because of ** at the end:
SyntaxError: invalid syntax
get_extension1 shoud be:
def get_extension1(filename):
output = filename.split(".")
return output[-1] if len(output)>1 else ''
Try it and find out:
get_extension1("myfile.ext")
Out[60]: 'ext'
get_extension1("myfile")
Out[61]: 'myfile' # wrong
get_extension2("myfile.ext")
Out[62]: '.ext'
get_extension2("myfile")
Out[63]: ''
get_extension3("myfile.ext")
Out[64]: 'ext'
get_extension3("myfile")
Out[65]: ''
Edit: it sounds like the AttributeErrors are because you are passing something other than a string for filename. If filename is a string they run just fine, but get_extension1 fails if the filename has no extension.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having really strange error. I am using Python 2.7 on Linux Mint OS. Here is the code:
with open(edgeClusteringPath) as f:
for line in f:
clustId = str(currCluster)
spl = line.split(" ")
# print spl
for i in spl:
# print i
(first, second) = edgeNodes[int(float(i))]
nodeClusters.setdefault(first, set())
nodeClusters.setdefault(second, set())
nodeClusters[first].add(clustId)
nodeClusters[second].add(clustId)
# print i
currCluster += 1
edgeClusteringPath is a path to a space separated data and edgeNodes is a dictionary with key = edgeId and value = (firstNode, secondNode). The problem occurs in the second for loop. This code gives me error:
> line 34, in <module>
(first, second) = edgeNodes[int(float(i))]
KeyError: 0
But when I uncomment one (or both) of the print i statements, the execution works fine (without error). It is really strange, I do not see how the print statement could affect the remaining code. I could uncomment the print statement, but I do not actually need that printing, so I would rather get rid of that line.
Here is a sample of edgNodes:
87388: (3250, 6041), 87389: (3250, 6045), 87390: (3250, 6046)
It is a huge dictionary, so I extracted only 3 key-value pairs.
Thank you in advance!
Edit:
Now my code works. I had problem with the paths I have been using. I used wrong file to initialize edgeNodes dictionary and it caused the problems. However, I posted the question just to see if anybody had idea how adding one line changes the behavior of the code. I have been using Java for 3 years and never had similar issue. I am new to Python and do not know how it works internally, so I wished to know if anybody has idea about the effect on one line of the other code.
Thank you for your opinions and suggestions!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Suppose that I would like my python program to accept 2 positional arguments:
1. The path to an input file
2.The path to a word dictionary, which is also a txt file.
Can anyone teach me how to go about doing that?
import sys
print('Name of the script: {0}'.format(sys.argv[0]))
if len(sys.argv) == 3:
inputfile_path = sys.argv[1]
dictionary_path = sys.argv[2]
print('First parameter: {0}'.format(inputfile_path))
print('Second parameter: {0}'.format(dictionary_path))
https://docs.python.org/2/library/sys.html
Your question is a bit vague so I'm just going to answer what I think you meant.
I'll assume that you have a function as such:
def function(string1, string2):
''' string 1 and string2 are paths to an input file and a dictionary respectively'''
Now in general to read a file you use:
file1 = open(string1,'r')
# After opening the file you loop over lines to do what you need to.
for line in file:
# Do what you need to
I'm not sure what you want to do with the input file so I'm going to leave it at that.
To load a dictionary from a string we use the eval() function. It actually runs a string. Now each line in the dictionary stored as a text file is a string so all you have to do is loop through the entire file (using the for line in file method from before) and run eval to get back a dictionary.
For example try this simple code:
#assume string2 is what you get back from the looping
string2 = str({'jack': 4098, 'sape': 4139})
dic = eval(string2)
print dic
Hopefully I've pointed you in the right direction. Since I'm not sure what exactly you need to do, I can't really help you more.