why does my code run in idle but not in vim? - python-2.7

i tried to run code in idle using F5 and it ran nicely
but i go to vim write the same code and do :!python and it gives this error
i know what indentetion is but it should not be giving it . how do i fix?
while True:
for i in range (90):
print (str (i) + "is a number smaller than 90")
break
now i run it vim and it gives this
File "<stdin>", line 2
^
IndentationError: expected an indented block
for i in range (90):
print (str (i) + "is a number smaller than 90")
break

Doing :!python % in Vim is essentially equivalent to doing $ python filename in your shell: the interpreter is fed a file and executes its content. What you get is not only perfectly normal and expected given the poor indentation of your file but also consistent:
# in Vim
:!python %
File "<stdin>", line 2
for i in range (90):
^
IndentationError: expected an indented block
# in your shell
$ python filename
File "<stdin>", line 2
for i in range (90):
^
IndentationError: expected an indented block
If anything, it is idle's reported behaviour that is surprising, here: your code is incorrect and can't be parsed by the python interpreter as-is so, if <F5> is really ignoring those errors and executing your code, then it means that it is doing something else than merely passing your file to the interpreter.
FWIW, this is what I get with your file in idle after pressing <F5>:
which is consistent with :!python % and $ python filename.

Related

How to use alternation operator in Vim + RipGrep?

I have the following in my .vimrc which (I believe) makes :grep within Vim use rg:
if executable('rg')
set grepprg=rg\ --no-heading\ --vimgrep\ --hidden\ --case-sensitive\ --ignore-vcs\ --glob\ '!.git'\ --glob\ '!node_modules'
endif
I want to search for all definitions of functions named render.... If I do
rg -e \(const\|let\)\ render .
on the command line, I get what I'm looking for.
But
:grep -e \(const\|let\)\ render
in vim results in
zsh:1: command not found: let) render
regex parse error:
(const
^
error: unclosed group
I've tried some other combos of \, putting the whole query in /.../, can't quite get it working.
How do I use the alternation operator in ripgrep in vim?
There are three pieces of machinery involved, here, each with its own idiosyncrasies: Vim, your shell, and RipGrep.
Ideally, this is how your pattern should look with RipGrep's syntax:
(let|const) render
If you try it as-is:
:grep (let|const) render
you should get a cascade of messages (irrelevant lines removed):
:!rg (let 2>&1| tee /var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/26
/opt/local/bin/bash: -c: line 1: syntax error near unexpected token `let'
/opt/local/bin/bash: -c: line 1: `rg (let 2>&1| tee /var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/26'
shell returned 2
E40: Can't open errorfile
/var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/26
Vim
The first line:
:!rg (let 2>&1| tee /var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/26
^^^^^^^
tells you that the command executed under the hood is:
rg (let
which is obviously incomplete. That is because Vim thinks that the | is a command separator (:help :bar) so it tries to execute the broken :grep (let. If you want your | to pass through, you must escape it:
:grep (let\|const) render
OK, all the arguments are now passed to rg:
:!rg (let|const) render 2>&1| tee /var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/27
^^^^^^^^^^^^^^^^^^^^^
Your shell
You are not done yet, though:
/opt/local/bin/bash: -c: line 1: syntax error near unexpected token `let'
/opt/local/bin/bash: -c: line 1: `rg (let|const) render 2>&1| tee /var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/27'
shell returned 2
E40: Can't open errorfile /var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/27
Your pattern includes a capture group delimited with parentheses, which confuses the hell out of your shell because it looks like an attempt to execute the command let|const in a subshell, which is bound to fail anyway, but in a context where it can't be done.
You can try to solve those problems by escaping things with backslashes but you are entering an escaping arms race between the shell and Vim. That is the kind of race where there is no winner.
A better approach is to wrap your whole pattern with single quotes:
:grep '(let\|const) render'
which tells your shell to treat what is between the quotes literally, without trying to be smart.
You can check what arguments are passed to rg by forcing an error:
:grep '(let\|const) render' foobar
which should show you this:
:!rg '(let|const) render' foo 2>&1| tee /var/folders/q4/8ckdmdb136z10l1nh7ss_hsw0000gn/T/vphU3gH/29
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Well done!
RipGrep
Without the single quotes, RipGrep wouldn't know that render is part of the pattern so it treats it as a filename and you get errors because that filename doesn't exist.
Wrapping the pattern in single quotes killed two birds with one stone: your shell expansion issue is solved and RipGrep knows where your pattern ends.
NOTE: While it is inconsequential, here, the -e flag is not necessary because your pattern doesn't start with a -.

python invalid syntax while reading line content of a file

I want to read a file line by line, but I have an error while reading it
with open("file.txt", "r") as f:
for line in f:
print line
The file file.txt contains only one line which is test example.
I got this error while executing the code above :
File "file.txt", line 1
test example
^
SyntaxError: invalid syntax
I just want to read the line content as a string, not as a variable or a command or anything else.
Oh my god I am stupid. The error came from a bad execute command. I was specifying arguments without the python file to execute ...
I think your code should probably be more along the lines of this:
with open("file.txt", "r") as f:
lines = f.readlines()
for line in lines:
print line
You have to make sure to actually read the lines as well. If you have any more issues, check out this great guide on reading and writing python text files:
http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
You can try this too, in Python 3:
f = 'file.txt'
with open(f) as f_obj:
for line in f_obj.readlines():
print(line)
In python 3.x the code is implemented as below
fr=open('file.txt','r')
for line in fr:
print line
So my suggestion is that to create a file object and use it in for loop

Full text is not printing to a text file in Python

I'm writing a program which parses text for specific words, and if these words are found, I'd print the line a and 4 lines after it, then search for the next sequence and do the same. When using print in the interactive terminal, it works, it prints all matching key words, however, when i try to write it to a text file, it writes one sequence and closes it. Any idea why or how I can print the full text showing in terminal in the text file instead of four lines only?
for j in os.listdir(path):
if os.path.isfile(os.path.join(path,j)) and 'nameoffile' in j:
print '\n'
print j
print '\n'
os.chdir(os.path.expanduser("~/Downloads/Windowslogs"))
file = open(j, 'r')
codes = 'error '
for line_app in appenforce_file:
if codes in line_app:
#print (line_app + ''.join(islice(appenforce_file, 4)))
with open("streamedlog.txt", 'w') as f:
f.write(line_app + ''.join(islice(appenforce_file, 4)))
with open("streamedlog.txt", 'w') as f:
That w flag tells open to "truncate the contents of the file, and write the following content there". You should either open the file before the start of the loop (and avoid opening it multiple times), or you should use the a flag instead, to append the file.

repr() output different in IDLE and Windows Powershell

Executing python ex1.py with ex1.py contents: print repr('foo') yields
'foo'
But executing repr('foo') on IDLE yields
"'foo'"
Alternatively, executing print repr('foo') on IDLE yields
'foo'
And executing python ex1.py with ex1.py contents: repr('foo') clearly yields
\n
For the former three cases...what's going on here?
repr('foo') is an expression whose value is the 5-character string 'foo'.
Therefore:
Printing the result of repr('foo') will display 'foo'.
Typing repr('foo') in a Python interpreter (such as IDLE's shell) will show the repr of 'foo', which is "'foo'".
Running a Python script containing just the code repr('foo') won't print anything, so you just get an empty output (the \n is likely added by your shell).
repr() - Return a string containing a printable representation of an object.
The output of print repr('foo') is 'foo'.
When you run it from the shell you get the output with-in quotes(string) => "'foo'"
When you run print repr('foo') from a python script you get the out string printed as => 'foo'
When you just put repr('foo') in your script you get nothing as you don't have a print statement to print the output.

python loop over subprocess.check_output by line

I need to loop over the output of a command. I thought I'd use subprocess.check_output, now I have two problems.
Here's a file:
foo
bar
Here's my python script:
import subprocess
for line in subprocess.check_output(['cat', 'foo']):
print "%r" % line
And here's what I get:
$ python subp.py
'f'
'o'
'o'
'\n'
'b'
'a'
'r'
'\n'
I expect:
$ python subp.py
'foo\n'
'bar\n'
subprocess.check_output(['cat', 'foo']) returns a string: "foo\nbar"
Thus, your for loop iterates over the string, printing every character, one-by-one.
The following should fix your problem:
import subprocess
print subprocess.check_output(['cat', 'foo'])
You can also do:
import subprocess
for line in subprocess.check_output(['cat', 'foo']).split('\n'):
print "%r" % line
With Python3 previous answer doesn't work immediately, because bytes are returned by check_output
Then you can either decode bytes into a string or split them immediately:
output = subprocess.check_output(['cat', 'foo'])
# splitting with byte-string
for line in output.split(b'\n'):
print(line)
# or decoding output to usual string
output_str = output.decode()
for line in output_str.split('\n'):
print(line)
Python3:
for line in subprocess.check_output(['cat', 'foo'], universal_newlines=True).split('\n'):
print(line)