I want to use vim to write Python2/3 code, and I want to know how I can compile and run from the editor? Does anyone have any good suggestions, thanks?
Pymode can run code using <leader>r. Here is a example:
If you're using vim writing Python 2 and Python 3, maybe you should compile a vim with +python2, and another one with +python3(then using the first one write python 2 code, the second one write python 3 code),
because Pymode and other plugin for python need +python2/3, but the problem is vim can't compile both with them.
I use a simple script to run python programs. All it requires is to have python installed on the machine. What it does ist run the program and show it's output in a overlay box in Vim. Problem is: if your program is interactive, it won't work. All it does ist display its output after the program is finished.
What I do is:
command! -complete=shellcmd -nargs=+ Shell call s:RunShellCommand(<q-args>)
function! s:RunShellCommand(cmdline)
let isfirst = 1
let words = []
for word in split(a:cmdline)
if isfirst
let isfirst = 0 " don't change first word (shell command)
else
if word[0] =~ '\v[%#<]'
let word = expand(word)
endif
let word = shellescape(word, 1)
endif
call add(words, word)
endfor
let expanded_cmdline = join(words)
botright new
setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap
"call setline(1, 'You entered: ' . a:cmdline)
call setline(1, 'CMD: ' . expanded_cmdline)
call append(line('$'), substitute(getline(2), '.', '=', 'g'))
silent execute '$read !'. expanded_cmdline
1
endfunction
This RunShellCommand runs a command and displays it in a popup within vim. Paste it in your vimrc.
For python I use this
nnoremap <silent> <leader>r :Shell python %:p<cr>
in <vimdir>/ftplugin/python.vim
With this all I have to do is use ,r (my <leader> is ,) and it runs the current open python file and shows its output.
Related
I hope I am able to describe my problem well, sorry in advance if it's complicated.
Question:
Does Python (or the os.path calls) automatically insert a return after an amount of characters?
Background:
I try to extract acoustic features from .wav files with the tool openSMILE.
For this purpose I pass the strings of the path (inputfile and outputfile)
via subprocess.
The SMILExtract call takes 3 arguments (-C for config; -I for inputfile -O for output file). I prepare these 3 Arguments with string operations and save the arguments in a list which gets passed to the subprocess call.
def extractFeatures(self,inputFile):
self.openSMILEsettings.append("-I " + inputFile)
outputFile = os.path.dirname(inputFile) + "/featuresOf_" +os.path.basename(inputFile)[0:-3] + "arff"
self.openSMILEsettings.append("-O " + outputFile)
print self.openSMILEsettings[2]
print ' '.join(self.openSMILEsettings)
# print subprocess.check_output(['SMILExtract'] + self.openSMILEsettings)
extractFeatures("/media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/audioFile.wav")
In the console the output of the print command (print ' '.join(...)) looks alright (example below)
-C OSconfig/IS12_speaker_trait.conf -I /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/audioFile.wav -O /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/featuresOf_audioFile.arff
However when I try to run the code with the subprocess call I get an exception. For debugging purposes I copied the output of the print to a text Editor and it appears that a Return gets entered, it looks like this
-C OSconfig/IS12_speaker_trait.conf -I /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/audioFile.wav -O /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/featur
esOf_audioFile.arff
This is word wrap, and is caused by your text editor. Essentially, there is no newline character, but your editor cannot show the text on a single line because it's too long. As a result, it's pushing the text to a new line.
You can disable this in gedit by going to View->Preferences->Uncheck "Enable Text Wrapping".
Thank you Dyno. That explains why there was a return in the texteditor.
I meanwhile found a solution for the exectuion of the SMILExtract call.
I changed subprocess call to os.system and used a template like explained elsewhere
The new call looks like this:
def extractFeatures(self,inputFile):
self.openSMILEsettings.append("-I " + inputFile)
outputFile = os.path.dirname(inputFile) + "/featuresOf_" +os.path.basename(inputFile)[0:-3] + "arff"
self.openSMILEsettings.append("-O " + outputFile)
cmd_template = 'SMILExtract {config_path} {wav_path} {arff_path}'
os.system(cmd_template.format(
config_path=self.openSMILEsettings[0],
wav_path=self.openSMILEsettings[1],
arff_path=self.openSMILEsettings[2],
))
This now runs smoothly. Is there any downside to using os.system insted of subprocess?
I am using Python 2.7.
I want to create a script to scan the text file for specific keywords like want to test and write or replace string (b3). My script:
#! usr/bin/python
import re
from os.path import abspath,exists
open_file = abspath("zzwrite.txt")
if exists(open_file):
with open(open_file,"r+") as write1:
for line in write1:
matching = re.match(r'.* want to test (..)',line,re.I)
if matching:
print ("Done matching")
write1.write("Success")
print >> write1,"HALELUJAH"
My input text file:
I just want to read 432
I just want to write 213
I just want to test b3 experiment
I just want to sleep for 4 hours
I managed to complete matching as there is a print "done matching" to indicates the codes are able to execute the last 'if' condition but no single string is written or replaced inside the text file. The string "b3" is different in every input text file so I do not prefer using str.replace("b3", "xx") method. Is there anything I missing in the script?
I am trying to create a translator-type program in Python (this is 2.7, if that is important). I want to receive user input, translate it, and then print their output to the screen. That part is not difficult, but I also want to export it to a text file. I am using Powershell for that, with the subprocess module. The Powershell script is very short, and all it does is asks for the user to copy and paste the Python translation into an input. It then calls New-Item to create a file and gives it the value option as the Python translation.
Python code:
def translator:
inquiry = raw_input("Leetspeak trans query: ") #Enter query
inquiry = inquiry.lower() #Change all to lowercase, so that everything gets translated
newPrint1 = "" #The new string that gets returned to them at the end
level = raw_input("What type of 1337 do you want? 1 for basic, 2 for intermediate, \
3 for intermediate-advanced, and 4 for ultimate.")
if level == "1":
from b4s1c_l33t import leetkey
elif level == "2":
from In73rm3d1473_1337 import leetkey
elif level == "3":
from In7_4DV import leetkey
from In7_4DV import combokey
elif level == "4":
from U17IM473_1337 import leetkey
from U17IM473_1337 import combokey
for char in inquiry:
if char in leetkey:
newPrint1 += leetkey[char]
else:
newPrint1 += char #Checks to see if the char is in the single-char list, then appends it accordingly
if int(level) >= 3:
for item in combokey:
if item in newPrint1:
newPrint1 = newPrint1.replace(item, combokey[item])
print newPrint1 #Print answer
question = raw_input(r"Do you want to translate some more? Type Y or N ") #Asks if they want to do more
question = question.lower() #Changes it to lowercase, for sending through the if loop
if question == "y" or question == "Y":
translator() #If answer is yes, program calls the entire function again
elif question != "y" and question != "n" and question != "Y" and question != "N":
print "I didn't quite catch that."
ps = raw_input("Would you like to export your leetness to a file? Type Y or N ")
if ps == "Y" or ps == "y":
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./1337Export.ps1\";", "&export"])
else:
print r"0|<. 600|)|3`/3!"
translator() #calls the function once
Powershell script:
Function export(){
$param = Read-Host("Copy-paste the translation from above here! ")
New-Item C:\Scripts\1337\1337ness.txt -type file -value $param
}
But I also know that the script was working perfectly up until I added the Powershell to it, so the problem is either in my usage of the subprocess module or in the Powershell script itself. I am a somewhat-medium-beginner at using Powershell, so any help will be greatly appreciated. Either that, or if there is a way to create the new file and write data to it in Python itself, that would be greatly appreciated.
Thanks,
Prem
Note: in the Python script, the leetkey and combokey are in separate files that are imported based on the value of the variable level.
UPDATE: I looked at the page here, and the subprocess code in the Python script is what I found in that page. It did not work, but instead threw an error saying that the export function does not exist, which it obviously does... in Powershell. Thanks again!
Your parameter construction is off. You want to run the following commandline in PowerShell:
. "./1337Export.ps1"; & export
which basically means "dot-source (IOW import) the script 1337Export.ps1 from the current working directory, then call (&) the function export".
The cleanest way to do this is to put the statement in a scriptblock:
&{. "./1337Export.ps1"; & export}
and pass that scriptblock as a single argument, so your Python statement should look like this:
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", '-Command', '&{. "./1337Export.ps1"; & export}'])
Of course you need to make sure that 1337Export.ps1 actually exists in the current working directory when you execute the Python script.
You have to do two things:
1) dot source the script (which is similar to python's import), and
2) subprocess.call.
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePS\";", "&export"])
Note: I have assumed that both the .py and .ps1 are residing in the same directory and the name of the powershell script is "SamplePS" and from that script I am using the function "export"
Hope it helps
I'm studying Python using Sublime Text 2.
I typed just the following two statements:
usr = raw_input('input any letters: ')
print usr
After pressing CMD+B, the following error message occurred.
input any letters: Traceback (most recent call last):
File "/Users/jun/Documents/workspace/studyPython/test.py", line 1, in <module>
usr = raw_input('input any letters: ')
EOFError: EOF when reading a line
[Finished in 0.3s with exit code 1]
How can I fix it? (I'm using Python 2.7.3 in OS X 10.8.2)
The problem is that raw_input isn't getting any input when you run the file in Sublime Text 2, so Python is throwing an error.
In the console that appears (where you see the error), there isn't anywhere for you to type in your arguments. You need to run the script at the command line to make it work. At a shell prompt (in OS X, probably Terminal, found in /Applications/Utilities/Terminal.app), type the following line:
python /path/to/script/test.py
The following line then appears:
input any letters:
with a cursor at the end of the line. This is prompting you to enter your raw_input, which allows it to set the use variable. You then type some text, for example:
input any letters: this is some text
and Python will print what you just typed:
this is some text
This doesn't work in SL2, because SL2 (afaik) doesn't have a way to offer you that prompt for raw_input.
I m trying to read two files and replace content of one file with content of other file in files present in folder which also has sub directories.
But its tell sub process not defined.
i'm new to python and shell script can anybody help me with this please?
import os
import sys
import os.path
f = open ( "file1.txt",'r')
g = open ( "file2.txt",'r')
text1=f.readlines()
text2=g.readlines()
i = 0;
for line in text1:
l = line.replace("\r\n", "")
t = text2[i].replace("\r\n", "")
args = "find . -name *.tml"
Path = subprocess.Popen( args , shell=True )
os.system(" sed -r -i 's/" + l + "/" + t + "/g' " + Path)
i = i + 1;
To specifically address your actual error, you need to import the subprocess module as you are making use of it (oddly) in your code:
import subprocess
After that, you will find more problems. I will try and keep it as simple as possible with my suggestions. Code first, then I will break it down. Keep in mind, there are more robust ways to accomplish this task. But I am doing my best to keep in mind your experience level and making it make your current approach as closely as possible.
import subprocess
import sys
# 1
results = subprocess.Popen("find . -name '*.tml'",
shell=True, stdout=subprocess.PIPE)
if results.wait() != 0:
print "error trying to find tml files"
sys.exit(1)
# 2
tml_files = []
for tml in results.stdout:
tml_files.append(tml.strip())
if not tml_files:
print "no tml files found"
sys.exit(0)
tml_string = " ".join(tml_files)
# 3
with open ("file1.txt") as f, open("file2.txt") as g:
while True:
# 4
f_line = f.readline()
if not f_line:
break
g_line = g.readline()
if not g_line:
break
f_line = f_line.strip()
g_line = g_line.strip()
if not f_line or not g_line:
continue
# 5
cmd = "sed -i -e 's/%s/%s/g' %s" % \
(f_line.strip(), g_line.strip(), tml_string)
ret = subprocess.Popen(cmd, shell=True).wait()
if ret != 0:
print "error doing string replacement"
sys.exit(1)
You do not need to read in your entire files at once. If they are large this could be a lot of memory. You can consume a line at a time, and you can also make use of what is called "context managers" when you open the files. This will ensure they close properly no matter what happens:
We start with a subprocess command that is run only once to find all your .tml files. Your version had the same command being run multiple times. If the search path is the same, then we only need it once. This checks the exit code of the command and quits if it failed.
We loop over stdout on the subprocess command, and add the stripped lines to a list. This is a more robust way of your replace("\r\n"). It removes whitespace. A "list comprehension" would be better suited here (down the line). If we didn't find any tml files, then we have no work to do, so we exit. Otherwise, we join them together in a space-separated string to be suitable for our command later.
This is called "context managers". You can open the file in a way that no matter what they will be closed properly. The file is open for the length of the context within that code block. We are going to loop forever, and break when appropriate.
We pull a line, one at a time, from each file. If either line is blank, we reached the end of the file and cannot do any more work, so we break out. We then strip the newlines, and if either string is empty (blank line) we still can't do any work, but we just continue to the next available line.
A modified version of your sed command. We construct the command string on each loop for the source and replacement strings, and tack on the tml file string. Bear in mind this is a very naive approach to the replacement. It really expects your replacement strings to be safe characters and not break the s///g sed format. But we run that with another subprocess command. The wait() simply waits for the return code, and we check it for an error. This approach replaces your os.system() version.
Hope this helps. Eventually you can improve this to do more checking and safe operations.