I'm working on a python script that need from the user to add an argument on the command line to call the script. The script is
#!/usr/bin/env python
import sys
if len(sys.argv) == 1:
sys.exit("Error : argument expected.")
print("coucou")
a = ['SDK', 'DESKTOP', 'DFEM', 'COMMAND', 'TOK', 'DESKTOPONLY']
z = a.count(sys.argv[1]
if z == 0:
sys.exit("Error : argument invalid.")
print (sys.argv[1])
and the error is
File "./test.py", line 10
if z == 0:
^
SyntaxError: invalid syntax
Can anybody help me ? :) I'm just starting python, and it's driving me crazy...
Related
**Can you tell me what is wrong with this error?***************
codio#random-media:~/workspace$ python final.py
File "final.py", line 4
return f'print("{phrase}")\n'
^
SyntaxError: invalid syntax
def createOutput(lang, phrase):
if lang == "python":
return f'print("{phrase}")\n'
if lang == "c++":
return f'cout << "{phrase}\\n";\n'
if lang == "c":
return f'printf("{phrase}\\n");\n'
return ""
F strings are not supported in python2.
Use format
'print("{}")\n'.format(var)
Or use Python 3.6+ and run the code
during tests it's showing the error message:
Traceback (most recent call last):
File "tictactoe/tictactoe.py", line 10, in <module>
coordinates = input("Enter the coordinates: ")
EOFError: EOF when reading a line
I can't image what is causing this problem. The code is:
c = True
while c:
coordinates = input("Enter the coordinates: ") # <-- line 10 is this one
if coordinates == '':
print("Coordinates should be from 1 to 3!")
continue
elif len(coordinates) < 3 or len(coordinates) > 3:
print("Coordinates should be from 1 to 3!")
continue
Thanks for support
Your test probably runs the code non-interactively. If you are creating the test in Python, try using subprocess.PIPE so that you can communicate with the subprocess. Without a valid stdin, the program will throw this error, which (should) cause your test to fail.
This question already has answers here:
Why must "exec" (and not "eval") be used for Python import statements?
(3 answers)
Closed 3 years ago.
Basically I am doing a POC against python eval security issue, but I am getting below error:
Traceback (most recent call last):
File "exploit.py", line 11, in <module>
a = paste()
File "exploit.py", line 6, in paste
if eval('%s > 1' % a):
File "<string>", line 1
import os;os.system('pwd') > 1
^
SyntaxError: invalid syntax
Code:
import datetime
def paste():
a = "import os;os.system('pwd')"
if eval('%s > 1' % a):
print a
else:
#create_brew(request.json)
return None, 201
a = paste()
print a
can anyone help me how to import libraries in-line?
eval works in expressions.
Use exec to execute a statement [import is a statement]
Also note, you cannot assign exec to a variable.
>> exec('import os;data = os.getcwd()')
>> print(data)
>> # /path/of/you/cwd
You may use the variable data to continue with your tests.
Taking the liberty to edit your code as follow:
def paste():
data = None
exec('import os;data = os.getcwd()')
if data:
return data
else:
return None, 201
a = paste()
print(a)
Hi I'm VERY new to programming, and I am working on my first program. I've been following along in a book and I decided to stop and test a function. The function is in a file called myPythonFunctions.py. I then created a new file called untitled.py and put it in the same folder as myPythonFunctions.py.
In untitled.py I have the following code:
import myPythonFunctions as m
m.generateQuestion()
Very simple, but when I try to run it I get Import Error: no module named myPythonFunctions.
I don't understand, there is clearly a file named myPythonFunctions in the folder. What's going on?
In case you need it, here is the code for m.generateQuestion()
def generateQuestion():
operandList = [0,0,0,0,0,]
operatorList = ['', '', '', '', '']
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
for index in range(0,5):
operandList[index] = randint(1,9)
for index in range(0,4):
if index > 0 and operatorList[index-1] !='**':
operator = operatorDict[randint(1,4)]
else:
operator = operatorDict[randint(1,3)]
operatorList[index] = operator
questionString = str(operandList[0])
for index in range(1,5):
questionString = questionString + OperatorList[index-1] + str[operandList[index]
result = eval(questionString)
questionString.replace("**","^")
print('\n' + questionString)
userAnswer=input('Answer: ')
while true:
try:
if int(userAnswer) == result:
print('Correct!')
return 1
else:
print('Sorry, the correct answer is', result)
return 0
except Exception as e:
print("That wasn't a number")
userAnswer = input('Answer: ')
Edit: I'm now getting this error
Traceback (most recent call last):
File "/Users/Brad/Desktop/Python/Untitled.py", line 1, in <module>
import myPythonFunctions as m
File "/Users/Brad/Desktop/Python/myPythonFunctions.py", line 33
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
^
SyntaxError: invalid syntax
The syntaxis error you are getting, is because you are trying to define a dictionary as a list, so the interpreter is raising the error because it does not know what to do with that.
To define a dictionary you need to use { } instead of [ ]
--- EDIT 2
Your dictionary implementation is wrong, do you really copied this code from somewhere?
The
operatorDict = {1:'+', 2:'-', 3:'*', 4:'**'}
Your code was mispelled
---- EDIT
Your code on myPythonFunctions is really bad.
Python needs correct identation to works, please double check this step
I suggest you to do a check in your structure:
I did this right now
/somefolder
--this.py
--functions.py
/
The contents
--this.py
import functions as f
print f.hello()
--functions.py
def hello():
return 'It worked'
Try this structure in your environment :D
And then run:
python this.py
I'm working with Python 2.7 and PyGTK 2.24. I am working with the following tutorial. Please read it for code context.
http://www.pygtk.org/pygtk2tutorial/sec-PackingDemonstrationProgram.html
The bottom block of code (reprinted below) is throwing the following error when I type it in (verbatum):
if __name__ =="__main__":
if len(sys.argv) != 2:
sys.stderr.write("usage: packbox.py num, where num is 1, 2, or 3.\n")
sys.exit(1)
PackBox1(string.atoi(sys.argv[1]))
main()
usage: packbox.py num, where num is 1, 2, or 3.
Traceback (most recent call last): File "C:/GTKTutorial/packbox.py",
line 161, in
sys.exit(1) SystemExit: 1
Additionally, if I change the code to the following to overcome the first error, I get the next error message:
if __name__ =="__main__":
if len(sys.argv) != 1:
sys.stderr.write("usage: packbox.py num, where num is 1, 2, or 3.\n")
sys.exit(1)
PackBox1(string.atoi(sys.argv[1]))
main()
Traceback (most recent call last): File "C:/GTKTutorial/packbox.py",
line 162, in
PackBox1(string.atoi(sys.argv[1])) IndexError: list index out of
range
What is wrong? How do I fix the code so I can work with the tutorial>
You need to call it from the command line with packbox.py 1, packbox.py 2, or packbox.py 3.
This will result in there being two arguments (the name of the program and the first thing you pass to it), so you won't trigger the sys.exit(1), and argv[1] will be a valid index access.
To run PackBox.py directly from IDLE,
REPLACE:
if __name__ =="__main__":
if len(sys.argv) != 2:
sys.stderr.write("usage: packbox.py num, where num is 1, 2, or 3.\n")
sys.exit(1)
PackBox1(string.atoi(sys.argv[1]))
main()
WITH:
if __name__ == "__main__":
packbox = PackBox1(3)
main()
To see all three example widget arrangements, substitute argument (3) with arguments (1) & (2). Click on X to exit the window; the Quit buttons aren't connected in this code.