Pycharm cannot recognize print option args - python

I am using PyCharm CE 2016.2 and python interpreter 3.5. When I tried to type the following in console, the file is generated with '123'.
>>> with open('man_data.txt', 'w') as data:
print('123', file=data)
However, when I put the same statement into a test.py file and try to run it using subprocess.call(['python', 'test.py']), it gives
>>> subprocess.call(['python', 'test.py'])
File "test.py", line 2
print('123', file=data)
^
SyntaxError: invalid syntax
1
Does anyone has any clues? Million thanks!

Python 2 is started when you call subprocess.call(['python', 'test.py']).
Try to change to subprocess.call(['python3', 'test.py']) or update the script as described here.

Related

Why does a python script behaves differently when it is run in pycharm and when it is run from a command prompt?

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.

Python3: File <stdin> TypeError: 'str' does not support the buffer interface

I know similar problems have been asked many times, but I don't think they solved my mine.
I'm basically trying to convert the following bash command into python using the subprocess module:
cat <a python file> | ssh <ip> python - <args>
Here's what I have:
with open('<the python file>', 'r') as python_file:
print(subprocess.check_output(['ssh', '<ip>', 'python - <args>', ], stdin=python_file))
And I'm running the above code from my local laptop using python3. When on the target machine (the remote server with <ip>) the python version is 2.7, this code snippet works fine. But if I switch the python version of the target machine to 3.4, I got the error:
File "<stdin>", line 114, in <module>
File "<stdin>", line 94, in main
File "<stdin>", line 22, in load
TypeError: 'str' does not support the buffer interface
I've tried the following:
open the python file with in binary mode: open('<a python file'>, 'rb')
change the subprocess args from ['ssh', '<ip>', 'python - <args>'] to ['ssh', '<ip>', 'python', '-', '<args>'].
But none of them worked. Can anyone give some suggestions? Thanks!
[Update]
Thanks to #Justin Ezequiel 's comment, this turned out to be a problem of '<the python file>' instead of the code snippet above. In '<the python file>' there is the following code:
columns = ['KNAME', 'TYPE', 'SIZE', 'MOUNTPOINT'] # (1)
lsblk_args = ['lsblk', '-i', '-n', '-o', ','.join(columns)] # (2)
output = subprocess.check_output(lsblk_args).strip() # (3)
parsed_res = _parse(output.split('\n'), columns) # (4)
And if I change the (3) line to
output = subprocess.check_output(lsblk_args).decode('utf-8').strip()
Everything works just fine.

SyntaxError on input() supposedly in Python 3

I have a script for sending emails using SMTP_SSL. The code is working fine in PyCharm but in the terminal I get an error.
This is the code:
import smtplib
s = smtplib.SMTP_SSL("smtp.googlemail.com:465")
mml=input("enter your email address :\n")
str(mml)
passr=input("enter your pass:\n")
str(passr)
s.login(mml,passr)
em = input("please type the email you want to send :\n")
str(em)
a = input("please type the message:\n")
str(a)
s.sendmail(mml,em,a)
print("\nEmail Was Sent..:)")
When I run this in my terminal its giving this after i enter the email:
enter your email address :
mahmoud.wizzo#gmail.com
Traceback (most recent call last):
File "medo.py", line 3, in <module>
mml=input("enter your email address :\n")
File "<string>", line 1
mahmoud.wizzo#gmail.com
^
SyntaxError: invalid syntax
When I am trying to put the email between quotes, e.g. "mahmoud.wizzo#gmail.com" its working fine.
How can I run my script in the terminal?
I suspect you're running your script using Python 2 on the command line. The behaviour of input() changed in Python 3.
Try running python3 my_file.py instead of python my_file.py.
This is actually the way Python works. The problem you have is that input takes input from the user and then "executes" or "compiles" it so if you enter 4+9 in the input it will produce the number 13. Not the string "4+9". So try using raw_input() in Python 2. You can also use sys.stdin.readline() to get a string I'm any Python version. Don't forget import sys.

Python: Run Script Under Same Window

I am trying to setup a program where when someone enters a command it will run that command which is a script in a sub folder called "lib".
Here is my code:
import os
while 1:
cmd = input(' >: ')
for file in os.listdir('lib'):
if file.endswith('.py'):
try:
os.system(str(cmd + '.py'))
except FileNotFoundError:
print('Command Not Found.')
I have a file: lib/new_user.py But when I try to run it I get this error:
Traceback (most recent call last):
File "C:/Users/Daniel/Desktop/Wasm/Exec.py", line 8, in <module>
exec(str(cmd + '.py'))
File "<string>", line 1, in <module>
NameError: name 'new_user' is not defined
Does anyone know a way around this? I would prefer if the script would be able to be executed under the same window so it doesn't open a completely new one up to run the code there. This may be a really Noob question but I have not been able to find anything on this.
Thanks,
Daniel Alexander
os.system(os.path.join('lib', cmd + '.py'))
You're invoking new_user.py but it is not in the current directory. You need to construct lib/new_user.py.
(I'm not sure what any of this has to do with windows.)
However, a better approach for executing Python code from Python is making them into modules and using import:
import importlib
cmd_module = importlib.import_module(cmd, 'lib')
cmd_module.execute()
(Assuming you have a function execute defined in lib/new_user.py)

"cannot execute binary file" error in python

I keep getting the following error:
$ ./test.py
-bash: ./test.py: cannot execute binary file
when trying to run the following file in python via cygwin:
#!usr/bin/python
with open("input.txt") as inf:
try:
while True:
latin = inf.next().strip()
gloss = inf.next().strip()
trans = inf.next().strip()
process(latin, gloss, trans)
inf.next() # skip blank line
except StopIteration:
# reached end of file
pass
from itertools import chain
def chunk(s):
"""Split a string on whitespace or hyphens"""
return chain(*(c.split("-") for c in s.split()))
def process(latin, gloss, trans):
chunks = zip(chunk(latin), chunk(gloss))
How do I fix this??
After taking on the below suggestions, still getting the same error.
If this helps, I tried
$ python ./test.py
and got
$ python ./test.py
File "./test.py", line 1
SyntaxError: Non-ASCII character '\xff' in file ./test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
There is a problem. You are missing the '/' in front of usr in #!usr/bin/python. Your line should look like this.
#!/usr/bin/python
In addition to protecting the file executable, #!/usr/bin/python may not work. At least it has never worked for me on Red Hat or Ubuntu Linux. Instead, I have put this in my Python files:
#!/usr/bin/env python
I don't know how this works on Windows platforms.

Categories