Search and replace in current file with Sublime Text plugin - python

I am trying to port a Sublime Text build system to a plugin.
The build system would receive the current file and go through it with this code:
for line in fileinput.input(inplace=1):
sys.stdout.write(makeReplacements(line))
Now, in the plugin syntax I go the fact that the way to get my current file's content is:
input = self.view.substr(
sublime.Region(0, self.view.size())
)
But now I'm not sure about what I should do about the next operation.
for line in input(inplace=1):
How could I make replacements in the file on-the-fly and then save it?

I don't think the Sublime Text plugin API can save the buffer, but you could use the file_name() method in the sublime.View class and work with the file directly.
As noted by #MattDMo, the file can be saved using view.run_command('save').
It may be easier to use the file name if your old build file worked with that.

As stated by #RazerM, the first argument has to be the file path. So for my example, this will work.
for line in fileinput.input(self.view.file_name(), inplace=1):
sys.stdout.write(self.makeReplacements(line))

Related

How to recognise text file from my linux pc via django code without checking its extension and also its file size? [duplicate]

This question already has answers here:
How to check type of files without extensions? [duplicate]
(10 answers)
Closed 6 years ago.
Most of the time when we create a new text file with gedit in linux then the file is not saved with an extension of .txt for text file.So how will I recognise it with django code because here I can't check file extension.Here is my code...
Let's say i have a resume field for each user in following models.py
class User(AbstractUser):
resume= models.FileField( upload_to=get_attachment_file_path,default=None, null=True,validators=[validate_file_extension])
Now i want to Validate the file for allowed extension so I made a
validators.py as below
def validate_file_extension(fieldfile_obj):
megabyte_limit = 5.0
filesize = sys.getsizeof(fieldfile_obj)
ext = os.path.splitext(fieldfile_obj.name)[1]
print("extensionnnnnnnnnnnnn",ext)
valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls','.txt','.odt']
if not ext.lower() in valid_extensions:
raise ValidationError(u'Unsupported file extension.')
elif filesize > megabyte_limit*1024*1024:
raise ValidationError("Max file size is %s Byte" % str(megabyte_limit))
Now whenever I upload a text file in my api then it says unsupported file type because the code is unable to get the extension of linux text file.So how can i recognise that text file which is not saved as demo.txt instead my text file is saved as only demo but it is text file as seen from property of that file.
Also my next question is to get the size of each file uploaded in that FileField.I am using PostgreSQL as Dbms
You probably want to detect the upload's MIME type regardless of file extension, and that's often done by reading the file header to detect "magic numbers" or other bit patterns indicating the true nature of a file. Often text files are an edge case, where no header is detected and the first x bytes are printable ASCII or Unicode.
While that's a bit of a rabbit hole to dive into, there's a few Python libraries that will do that for you. For example: https://github.com/ahupp/python-magic will work for your needs by simply inferring the mime type per the file contents, which you will then match against the types you want to accept.
A somewhat related set of example code specific to your needs can be found here: https://stackoverflow.com/a/28306825/7341881
Edit: Eddie's solution is functionality equivalent; python-magic wraps libmagic, which is what Linux's native "file" command taps into. If you do decide to go the subprocess route, do be extra careful you're not creating a security vulnerability by improperly sanitizing user input (eg the user's provided filename). This could lead to an attack granting arbitrary access to your server's runtime environment.
Easy 3 line solution with no external dependencies.
import subprocess
file_info = subprocess.getoutput('file demo')
print(file_info)
In POSIX systems (Linux, Unix, Mac, BSD etc) you can use a file command, for example file demo will display the file info even if the file extension is not explicitly set.
demo is the argument for the file command in other words the actual file you are trying to detect.
Disclaimer, be extra careful running external commands.
Please follow this link for more info about the Python subprocess module.
https://docs.python.org/3.6/library/subprocess.html

Line comments in Pycharm

Hi when I comment out a line in Pycharm using the ctrl+slash keyboard shortcut, I get
# code
but instead I want
##Code
like in IDLE.
Is this possible?
You can register a new file type and at the time of registration specify comment characters. You need to reassign *.py to this new type from the default Python file type that comes with installation.
Step by step procedure:
Ctrl+Alt+S to open File Types dialogue.
Alt+Insert (or click on +) to create a new file type
In the new File Type dialogue for Syntax Highlighting -> Line comment: provide ##
Provide rest of the details (including Name and Description) as needed and click OK.
Select the newly created File Type and in Registered Patterns section click + to add a wildcard.
In Add wildcard dialogue box enter *.py and click Ok
Since *.py is already assigned to the default type you will be asked to confirm Reassign wildcard. Do so.
Apply and Ok
Note: We have to do all this because we can not edit default file types and Python is a default file type.
Now, open a Python file (.py extension) and check Ctrl+Slash on any line. You should now see ## prepended to the line.
Ctrl+Slash on any line comments the line i.e. Ctrl + /

How do I mark a .txt file as "not executable"?

I am hosting a text file on OpenShift inside the cron/minutely directory. The server is trying to run the text file every minute, only I don't want it to: all I want the text file to do is stay on the server so I can save useful information inside it.
How do I tell the server that I want it to ignore the text inside the file instead of running it as code? Is there a way to do it by adding a specific "shebang" line at the beginning? Is it even possible to keep the text file in the cron/minutely directory without it being executed?
Thank you.
You can add this as the first line of the text file:
#!/usr/bin/true
That's a sort of fake shebang line. It means that if the file is executed, the "interpreter" to "run" the file is the true program, which is a trivial program which does nothing but return the status code for success (0).
Therefore, a true shebang will make any file "successfully" execute, but do nothing.
Please don't take this to mean that leaving data files in a directory meant for executables is a good idea; it's not. This is just a hack of last resort.

How to get python to read a file that has been opened through File Explorer?

I don't exactly know how to phrase this question, but I have tried my best.
Let's say I have an application and I have set it to be the default to run when the .example file extention has been double clicked within File Explorer. Now, how do I get this application not to just launch, but instead to react as if it has been asked to open the file. Now I know there is the:
file = open ("C:\\ExampleFolder\\ExampleFile.example)
file = file.read()
method of reading a file but how would I get the program to run this script when the program is launched by the opening of a file and in which way would I get the program to know the location of the opened file? I know that there are questions about setting a python app to the default but I have found nothing, if I am asking the question right, on completing the above on stackoverflow or a Google search. Or I am just looking at this wrong or asking the question wrong?
I'm not sure this might be what you are looking for. You can check whether, double clicking on a file with extension .example which you have linked to your program, means that an argument is passed to your program: the file name being opened. You can check whether this is the case by:
import sys
print sys.argv
#if that is meaningless, try printing every single argument passed to the script
#I can't recall whether len(sys.argv) is also = sys.argc!
for x in xrange(len(sys.argv)):
print sys.argv[x]
I hope this is of some help!

Python file to open a text file and run other python files in the text file

I have a text file inside which I have paths to a few python files and the arguments that I would specify when I run them in a command prompt.
I am looking for a python script that opens up the text file and runs the python programs specified in the text file along with the provided arguments.
The text file will look something like
`C:\hello.py world
C:\square.py 5`
i think you should refer to below :
Calling an external command in Python
Step One
read all lines in your command file get a list of python script file name and arguments
like: " C:\hello.py and argument: word "
Step Two
call them in below code style
from subprocess import call
call(["python C:\hello.py", "word"])
......
I don't think this post deserves down voting. But from now on I would suggest to OP to look for a solution yourself, and then if you can't find the answer post on stack overflow!
from subprocess import call
with open("somefile.txt", 'r') as f:
some_files_to_run = [line.split('\n')[0] for line in f.readlines()]
for file_to_run in some_files_to_run:
call(["python", file_to_run])

Categories

Resources