I'm trying to run a python script in the Mac Terminal with python test.py.
The problem is that I getting this error:
Traceback (most recent call last):
File "test.py", line 3, in <module>
import agent as a
File "/home/test/script/agent.py", line 5
budget: None
^
SyntaxError: invalid syntax
why this line budget: Noneis giving a SyntaxError?
the original code:
class Agent:
budget: None
budget_left: None
(....)
When I run the script in PyCharm works just fine.
It's giving a syntax error because, well, that is invalid syntax. You don't define attributes like that; you need to use assignment.
class Agent:
budget = None
budget_left = None
Note, though, defining these as class attributes probably isn't what you want.
Just put '=' for the variables and you are done.
budget = None
Read this for more on the topic:
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
Related
I run my bash script my_file.sh in a python file as follows:
import subprocess
def rest_api():
params = {
'query': 'indepedence day',
'formats': '["NEWSPAPER"]',
}
subprocess.call(['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}',
f'LANGUAGE={params.get("lang")}', # returns None!
])
if __name__ == '__main__':
rest_api()
Several of my input arguments in subprocess.call do not normally exist in a dictionary params={} (here I provided f'LANGUAGE={params.get("lang")}' as one example). I handle such unavailability in my_file.sh to initialize with something, for instance:
if [ -z "$LANGUAGE" ]; then LANGUAGE="${LANGUAGE:-[]}"; fi
What I want is to apply some sort of if else statement in subprocess.call function with this logic:
if params.get("lang") is None, do not even send it as an input to bash file, e.g., treat it as I never provided such input for my_file.sh.
Therefore, I tried to rewrote my code like this:
subprocess.call(['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}',
if params.get("lang"): f'LANGUAGE={params.get("lang")}', # syntax Error
])
which is wrong I get the following invalid syntax error:
Traceback (most recent call last):
File "nationalbiblioteket_logs.py", line 13, in <module>
from url_scraping import *
File "/home/xenial/WS_Farid/DARIAH-FI/url_scraping.py", line 17, in <module>
from utils import *
File "/home/xenial/WS_Farid/DARIAH-FI/utils.py", line 53
if params.get("lang"): f'LANGUAGE={params.get("lang")}',
^
SyntaxError: invalid syntax
Do I have a wrong understanding of applying if else statement for the input arguments of a python function or is there an easier or cleaner way doing it?
Cheers,
You can specify the default when calling .get(), so use an empty string.
f'LANGUAGE={params.get("lang", "")}'
If you don't want the LANGUAGE= argument at all when no value is provided, you need to build the list dynamically.
cmd = ['bash',
'my_file.sh',
f'QUERY={params.get("query")}',
f'DOC_TYPE={params.get("formats")}']
if (lang := params.get("lang")) is not None:
cmd += [f'LANGUAGE={lang}']
subprocess.call(cmd)
I'm getting an error when I run a script from the Linux command prompt(bash), but when I run the same script in the Pycharm directly, it works fine.
Here is the code:
class EncodeKey:
def __new__(cls, *args):
if len(args) == 1:
return cls.generate_encode_key(args[0].upper())
return cls.get_encode_key(args)
...
...
if __name__ == '__main__':
encode_key = EncodeKey(*["something"])
print(encode_key)
As I already told, in the Pycharm the script works fine without any errors, but here is what I'm getting when the script is run from the command prompt:
user#machine:~/my/path/to/the/script$ python py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments
Or:
user#machine:~/my/path/to/the/script$ ls -lh
...
-rwxrwxr-x 1 user user 3.2K Jun 20 19:12 py.py
...
user#machine:~/my/path/to/the/script$ ./py.py
Traceback (most recent call last):
File "py.py", line 93, in <module>
encode_key = EncodeKey(*["something"])
TypeError: this constructor takes no arguments
Of, course, I didn't find any solutions on such an unusual problem. Any ideas why is that happening ? And how to solve it ? Thanks !
If you've installed python in the default way, the python command uses Python 2. To interperet with Python 3, use the command python3:
user#machine:~/my/path/to/the/script$ python3 py.py
The program errors in Python 2 because old-style classes, the default in Python 2, do not support __new__. If you need to support Python 2, make your class new-style by extending object:
class EncodeKey(object):
Your code will still work in Python 3 if you do this.
Can't instantiate objects using python interpreter, please help.
So inside of my python file expresser.py I have something like
class Expresser:
def __init__(self):
pass
...
Now when I type in the terminal
python
and then
>>> import expresser
>>> test_object = Expresser()
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Expresser' is not defined
I'm using PyCharm
when I type where python I get three diff locations so I suspect that but don't know how to rectify
I guess you meant:
from expresser import Expresser
Or:
from expresser import *
This is my first time doing unit testing and i'm trying to run a simple code...
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)
then i get the error message...
Traceback (most recent call last):
File "/Users/s66/Desktop/unittest.py", line 2, in <module>
import unittest
File "/Users/s66/Desktop/unittest.py", line 4, in <module>
class TestSequenceFunctions(unittest.TestCase):
AttributeError: 'module' object has no attribute 'TestCase'
>>>
How do I fix this?
That's because your script name is called unittest.py. The statement import unittest is importing your script rather than the unittest module, hence the error with the non-existant TestCase attribute.
For more info, see the docs for Module Search Path. In short, when you do an import, built-in modules are first searched followed by directories listed in sys.path. This usually starts with the location of the running script followed by PYTHONPATH and THEN then default modules directory
In your case, since unittest is not a built-in, it found your script (and loaded it) before it could search for other installed modules.
How do I fix this?
Rename your script.
Do you have a module in the directory where you're running your script that is called unittest.py?
When I run your code I get the following output.
test_choice (__main__.TestSequenceFunctions) ... ok
test_sample (__main__.TestSequenceFunctions) ... ERROR
test_shuffle (__main__.TestSequenceFunctions) ... ok
======================================================================
ERROR: test_sample (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 23, in test_sample
with self.assertRaises(ValueError):
TypeError: failUnlessRaises() takes at least 3 arguments (2 given)
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (errors=1)
My answer is not intended for this author, but for people that found this stackoverflow page on Google for the same error message but for a different reason.
I was upgrading from django 1.5 to django 1.10, and the "import unittest" in one of my test files was causing a similar error.
The error was due to the app/tests/init.py file which was importing the errored test file (this was necessary in django 1.5 as the automatic detection of test files didn't exist at that time. Now it is no longer required).
So the solution was to simply empty the init.py file and it solved the issue.
Hope it can help some people as I lost 30mn to 1h on this issue.
I have a python module that consists of many function definitions, all static. Then at the end I added a class definition however, the interpreter presents me with the following error:
Traceback (most recent call last):
File "~/file.py", line 136
class InvalidPredicateError(Exception):
^
SyntaxError: invalid syntax
I don't see a problem with this at all. Is it because I'm trying to define a class in a static module?
You have an error on the line(s) before the class. For example:
$ cat -n pyinvclass.py
1 def f():
2 return (1, 2
3
4 class InvalidPredicateError(Exception):
5 pass
$ python pyinvclass.py
File "pyinvclass.py", line 4
class InvalidPredicateError(Exception):
^
SyntaxError: invalid syntax