Sublime Text custom build system with command line - python

Does anyone have some experience with custom build systems in Sublime Text 3, especially with python as a base?
At the moment I struggle here with the problem that a extern command line program should be called for baking the file of user.
My current ".sublime-build" looks like this:
{
"target": "convert2libpart",
"selector": "text.xml.gdl"
}
The target is set to the python file,
which is this:
from __future__ import print_function
import sublime
import sublime_plugin
import os, os.path
from subprocess import call
# convert the current XML to binary via
# the converter -> who does actual work
class convert2libpart(sublime_plugin.WindowCommand):
def run(self, cmd="", file_regex="", path=""):
view = self.window.active_view()
self.plat = sublime.platform()
# get the settings
s = sublime.load_settings("somesettings.sublime-settings")
version = s.get("version") # this is from a settingsfile, as you can see
version = str(version)
if self.plat == "windows":
converter_path = "C:\\Program Files\\folder " + version + "\\"
#else:
# osx path... (program is available on both systems)
file_name = os.path.basename(view.file_name())
dir_path = os.path.dirname(view.file_name())
# XMLConverter xml2libpart source dest
cmd = "XMLConverter.exe xml2libpart " + "\"" + dir_path + "\\" + file_name + "\"" + " " + "\"" + dir_path + "output" + "\""
proc = call("start cmd /K " + cmd, cwd=converter_path, shell=True)
If I use this build system I can see in the task manager that the converter will start, but the output is not generated. Is it the program's fault?
Doing this manually with exact same command will produce the desired output.
Any thoughts? Thanks in advance.

Related

how to use "code ." command in python script

I have made a piece of code to automate making a new project. I ahve mangaged to create the file in a location I like, create the file and create a test python file. How would I open that file in vs code?
import subprocess,os,time
projectName = input("What is the name of the project?\n")
filename = "test"
fileEx = '.py'
os.chdir('../')
os.chdir('../')
os.chdir('../')
os.chdir('.\Documents\ ')
os.chdir('.\programs\ ')
project = subprocess.Popen(["powershell","md",projectName])
file = filename + fileEx
fileLoctaion = os.getcwd() + file
d = os.getcwd() + f'\{projectName}\ '
time.sleep(1)
os.chdir(d)
with open(file, 'w') as fp:
pass
You could try the following:
import os
os.system("code NAMEOFFILE.py") ## the "code" command is the command used to open a file with vsc in a command line interface.
You can do the same thing with subprocess:
import subprocess
subprocess.getoutput("code NAMEOFFILE.py")

subprocess error in python

I'm using PDFminer to convert pdf to html file.
Wrong Code:
def pdf2html(filename, path):
outfile_name = filename.split('.')[0] + '.html'
cmd = ['pdf2txt.py', '-o', path + outfile_name, path + filename]
print ' '.join(cmd)
subprocess.call(cmd, shell=True)
filename = "040214_MOOCs.pdf"
path = "/Users/andy/GoogleDrive/Debate/intelligencesquaredus/data/"
pdf2html(filename, path)
The above code is supposed to run "pdf2txt.py -o /Users/andy/GoogleDrive/Debate/intelligencesquaredus/data/040214_MOOCs.html /Users/andy/GoogleDrive/Debate/intelligencesquaredus/data/040214_MOOCs.pdf"
in the shell.
But there's no output(040214_MOOCs.html) using above code. If I run the command in shell, it generates output with no problem.
Then I tried following script and it works, the only difference is using os.system instead of subprocess.call:
def pdf2html(filename, path):
outfile_name = filename.split('.')[0] + '.html'
cmd = ['pdf2txt.py', '-o', path + outfile_name, path + filename]
print ' '.join(cmd)
os.system(' '.join(cmd))
filename = "040214_MOOCs.pdf"
path = "/Users/andy/GoogleDrive/Debate/intelligencesquaredus/data/"
pdf2html(filename, path)
Also, in wrong code, if I set shell=False, the code also works, why that's the case?
Why subprocess doesn't work in this case while os.system works?
Very confusing, need explanation.
This is likely because of shell mismatch. Can you try running your subprocess call without shell=True?

Python error: path is not recognized as an internal or external command, operable program or batch file

import sys
import os
import shutil
def main(argv):
if len(argv) < 3:
print("To few arguments")
return 1
dir = os.path.dirname(__file__)
latencyMonitorDir = argv[1]
feedManagerDir = argv[2]
if not os.path.exists(dir + r"\Data"):
os.makedirs(dir + r"\Data")
if not os.path.exists(dir + r"\Data\Result"):
os.makedirs(dir + r"\Data\Result")
scriptCommand = "\"" + dir + "\\script.py\" " + latencyMonitorDir
os.system(scriptCommand)
if not os.path.isfile("\"" + dir + "\\Data\\BoostedFeedManager.exe\""):
shutil.copy(feedManagerDir + r"\BoostedFeedManager.exe", dir + "\Data")
scriptCommand = "\"" + dir + "\\Data\\BoostedFeedManager.exe\" " + "\"" + dir + "\\Data\\configInstruments.json\""
print("debug")
print(scriptCommand)
os.system(scriptCommand) # Error
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
It makes error:
path is not recognized as an internal or external command, operable program or batch file.
This error emerges when I don't add quotes to path, but I'm doing it. Place of error is marked by commend "#Error".
From the documentation
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.
Because if the error, the path probably doesnt exist, or it not a command/program. Try with os.path.exist(scriptCommand) if it exist.
using subprocess.getoutput('cmd')

Python Backup script not working on windows

I have created a backup script that creates zip of folders. This script is working on linux but not on Windows. Please help.
import os
import time
source = 'D:\\backup_original'
target_dir = 'E:\\backup_copied'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip {0} {1}".format(target, ''.join(source))
os.system(zip_command)
On windows, zip is not installed by default. You need to install 7 zip, command line. I have modified your script.
import os
import time
source = 'D:\\backup_original'
target_dir = 'E:\\backup_copied'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "7za a {0} {1}".format(target, ''.join(source))
if os.system(zip_command) == 0:
print('Success')
else:
print('Backup Failed')
Are you sure this script was working on linux? u have used "zip a"? You must have copied it from somewhere.

copying logs in python using the command line function

I had a doubt with my code which i think I can verify here . My requirement is to copy the apache log and error log from two different servers . Iv written down a python program, using a for loop.
My code:
def copylogs(Appache,Errorlog, folder_prefix) :
root_path = '/home/tza/Desktop/LOGS/'
folders = ['Appache','Errorlog']
for folder in folders:
folder_name = folder_prefix + "_" + folder + str(int(time.time()))
mkdircmd = "mkdir -p " + root_path + "/" + folder_name
os.system(mkdircmd)
filePath = root_path + folder_name
serverPath = "/var/log/apache/*"
cmd = "scp " + "symentic#60.62.1.164:" + serverPath + " " + filePath
cmd = cmd.replace("60.62.1.164" ,myip1)
cmd = os.system(cmd)
print "Logs are at:",root_path+folder_name
time.sleep(10)
filePath = root_path + folder
serverPath = "/var/log/errorlog/*"
cmd = "scp " + "symentic#10.95.21.129:" + serverPath + " " + filePath
cmd = cmd.replace("10.95.21.129" ,myip2)
cmd = os.system(cmd)
print "Logs are at:",root_path+folder_name
now Im calling the function at the end of my program :
folder_prefix = "Fail Case-1"
copylogs(Appache,Errorlog, folder_prefix)
I have an issue here . Programm executes successfully but the logs get overwritten .what i mean is first Appache folder gets created ,logs are copied and then once again it gets overwritten .
What i require is : create a folder Appachelogs[with the timestamp as defined ] ,copy the logs from machine one , next copy error logs from machine2 , and continue the program
How can this be achieved?
scp by default overwrites if a same file name exists in the target computer.
I would suggest using a combination of a error file name + the timestamp for naming the error logs. It's always a good convention for logs to have a timestamp in the name and they also prevent the overwriting problem you are experiencing.
Consider using rsync instead of scp
Do your logs have the same filenames on both machines? scp will overwrite them if they do.
Personally I would have two directories, one for each machine. Or use a timestamp as suggested by Sylar in his answer.

Categories

Resources