I can't run python3 program in vim - python-3.x

I did a very simple program :
a = input("Enter a number A : ")
b = input("Enter a number B : ")
print("Below 2 strings concateneted :")
print(a + b)
When i run it from bash, i write :
python3 <my_program.py>
It works well
When i run it from vim, i open "my_program.py" in vim and then write :
:w !python3
It crashes and gives me this message :
Enter a number A : Traceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError: EOF when reading a line
when i run it from a terminal opened from vim, i write :
:terminal
then
python3 <my_program.py>
This works.
Why i can't execute python3 programs from vim ?
EDIT : it's linked with the input function. If i directly assign variables it works. More information are welcome.

It's because of the input function in my python script.
Because i want to keep this function. No choice, open a separate terminal.
By the way, it's be possible to open the terminal in VIM (for convenience) writing in VIM normal mode :
:vert term

Related

Python3 EOFError: EOF when reading a line (Windows)

I am trying to take input() from keyboard but EOFError is received.
Does anyone know how to solve this issue?
test.py
import sys
if sys.stdin.isatty():
print("keyboard input is working")
else:
print("keyboard input is not working")
# read all input from stdin
data = sys.stdin.read()
print(data)
r = input("Enter something here:")
print(r)
Now, create a dummy text file and pass it to python
#dummy.txt
dummy text goes here.
I then called the python script on Windows using this command:
C:\> test.py < dummy.txt
This is the error I received:
keyboard input is not working
dummy text goes here.
Enter something here:Traceback (most recent call last):
File "C:\test.py", line 11, in <module>
r = input("Enter something here:")
EOFError: EOF when reading a line
C:\>
I kind of know how to solve this issue in Linux by open a file descriptor on /dev/tty and pass it back to sys.stdin but how do I archive this on Windows?
I notice function msvcrt.getch() could work, but there should be a better solution that I can utilize input() function for cross-platform compat.
Please help, anyone!

VIM: EOFError: EOF when reading a line input python

I'm trying to add input to my python code
isAge = input("Enter your age: ")
and it shows me the following error:
enter your age: Traceback (most recent call last):
File "test2.py", line 3, in <module>
isAge = input("enter your age: ")
EOFError: EOF when reading a line
I use "w !python" to run the code.
I tried w !python 18" Where 18 is the age number, but it didnt work
If you use :w !python from Vim, it will start a Python interpreter and pipe the script to the interpreter, which means the Python interpreter's standard input will be connected to this pipe through which Vim will send it the script, and not to the console.
So Python functions such as input() will not work to read input from the user, since the interpreter does not have its standard input connected to the console.
To solve this, instead of having Vim pipe the script to a Python interpreter, have it invoke the Python interpreter with the script as an argument. So instead of :w !python, use:
:w
:!python %
This assumes you're editing a file and not an unnamed buffer. If you have an unnamed buffer, then save it to a *.py first.

How to print ダイスキ using Python 3.7 in Scite?

I'm using Win10 & Scite with utf-8 enabled output window.
The file is saved as UTF-8 with BOM
Script:
print('ダイスキ from python 3')
The script can be run on cmd prompt without error. But when run on Scite it will produce error:
Output:
>pythonw.exe -u "test.py"
Traceback (most recent call last):
File "test.py", line 12, in <module>
print('\u30c0\u30a4\u30b9\u30ad from python 3')
File "D:\BIN\Python37\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1-2: character maps to <undefined>
>Exit code: 1
How to properly print ダイスキ to stdout using python3 with Scite?
Updates:
I've edited Scite Global Options file, to support utf-8.
code.page=65001
I've tested C, Lua, old Python 2.7, and it can print utf-8 strings (on Scite output window).
Seems to be Scite configuration error or a maybe Scite bug, because the Scite output terminal window works on Lua & C, but fail only on Python3.
Scite involves popen() / piping the STDOUT.
Python 3.7 need env variable "PYTHONIOENCODING" to be set manually. So you need to add environment variable "PYTHONIOENCODING" set to "utf_8"
Result:
Try to do this:
print(u'ダイスキ')

Python3.4 -Nmap Requires root privileges

Running on Mac Os 10.10.5
Running this script to scan for hosts on the network:
import nmap
nm = nmap.PortScanner()
nm.scan('192.168.5.1/24', arguments='-O')
for h in nm.all_hosts():
if 'mac' in nm[h]['addresses']:
print(nm[h]['addresses'], nm[h]['vendor'])
When running it its printing:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 290, in analyse_nmap_xml_scan
dom = ET.fromstring(self._nmap_last_output)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/xml/etree/ElementTree.py", line 1326, in XML
return parser.close()
File "<string>", line None
xml.etree.ElementTree.ParseError: no element found: line 1, column 0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/*/Documents/*.py", line 3, in <module>
nm.scan('192.168.0.0/24', arguments='-O')
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 235, in scan
nmap_err_keep_trace = nmap_err_keep_trace)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 293, in analyse_nmap_xml_scan
raise PortScannerError(nmap_err)
nmap.nmap.PortScannerError: 'TCP/IP fingerprinting (for OS scan) requires root privileges.\nQUITTING!\n'
I tried going to that directory and running this command in the terminal:
sudo python *.py
({'mac': '02:62:31:41:6D:84', 'ipv4': '192.168.5.1'}, {})
Any suggestions to run the script from the python IDLE?
Running IDLE as root might work, but it might not be a great idea. sudo idle
Option 1 (recommended):
Put the code requiring elevated privileges in a python file which you run with sudo. I assume you want to play with the results, so you could have the script save the results to a file, which you then read in IDLE.
The following code works in python 2.7 and 3.4
import nmap
import json
nm = nmap.PortScanner()
nm.scan('192.168.5.1/24',arguments='-O') #Note that I tested with -sP to save time
output = []
with open('output.txt', 'a') as outfile:
for h in nm.all_hosts():
if 'mac' in nm[h]['addresses']:
item = nm[h]['addresses']
if nm[h]['vendor'].values():
item['vendor'] = list(nm[h]['vendor'].values())[0]
output.append(item)
json.dump(output, outfile)
Run sudo python nmaproot.py
Since the file is written by root, you need to change ownership back to yourself.
sudo chown -r myusername output.txt
In IDLE:
import json
input = open('output.txt','r'):
json_data = json.load(input)
json_data[0] # first host
Option 2 (not recommended at all):
Use subprocess to run the file with the elevated code as root and return the output. It gets kind of messy and requires you to hardcode your password...but it's possible.
from subprocess import Popen, PIPE
cmd = ['sudo', '-S', 'python', 'nmaproot.py']
sudopass = 'mypassword'
p = Popen(cmd, stdin=PIPE, stderr=PIPE,universal_newlines=True, stdout=PIPE)
output = p.communicate(sudopass + '\n')
I'm unsure of how you can run a given portion of your python code as root without saving it to a file and running it separately. I recommend you go with option 1 as option 2 isn't very good (but it was fun to figure out).
Copy the idle desktop shortcut and name it rootidle then right and change properties. Goto desktop entry and add gksu before /usr/bin/idle3. Then load and run the program
maybe this might help someone here. Found this from one site
scanner.scan(ip_addr, '1-1024', '-v -sS', sudo=True)
use
sudo = True

Execute command on linux terminal using subprocess in python

I want to execute following command on linux terminal using python script
hg log -r "((last(tag())):(first(last(tag(),2))))" work
This command give changesets between last two tags who have affected files in "work" directory
I tried:
import subprocess
releaseNotesFile = 'diff.txt'
with open(releaseNotesFile, 'w') as f:
f.write(subprocess.call(['hg', 'log', '-r', '"((last(tag())):(first(last(tag(),2))))"', 'work']))
error:
abort: unknown revision '((last(tag())):(first(last(tag(),2))))'!
Traceback (most recent call last):
File "test.py", line 4, in <module>
f.write(subprocess.call(['hg', 'log', '-r', '"((last(tag())):(first(last(tag(),2))))"', 'work']))
TypeError: expected a character buffer object
Working with os.popen()
with open(releaseNotesFile, 'w') as file:
f = os.popen('hg log -r "((last(tag())):(first(last(tag(),2))))" work')
file.write(f.read())
How to execute that command using subprocess ?
To solve your problem, change the f.write(subprocess... line to:
f.write(subprocess.call(['hg', 'log', '-r', '((last(tag())):(first(last(tag(),2))))', 'dcpp']))
Explanation
When calling a program from a command line (like bash), will "ignore" the " characters. The two commands below are equivalent:
hg log -r something
hg "log" "-r" "something"
In your specific case, the original version in the shell has to be enclosed in double quotes because it has parenthesis and those have a special meaning in bash. In python that is not necessary since you are enclosing them using single quotes.

Resources