Opening file - Performing a function - python

I was wondering if someone could give me a direction on how to give functions to a file... This is a bit hard to explain, so I'll try my best.
Let's say I have an application (using wxPython) and let's say that I have a file. Now this file is assigned to open with the application. So, I double-click the file and it opens the application. Now my question is, what would have to be written on the file to, for example, open up a dialog? So we double-click the file and it opens a dialog on the application?
PS: I know that I have first to associate the program with a certain file type to double-click it, but thats not the question.

AFAIK most platforms just call the helper app with the file you clicked on as an argument, so your filepath will be in sys.argv[1]

I think what he wants to do is associate a file extension to his application so when he opens the file by double clicking it, it sends the contents of the file to his app; in this case, display the contents within a Dialog?
If this is the case, than the first thing you would need to do (provided you are on windows) is create the appropriate file association for your file extention. This can be done through the registry and when setup correctly will open your app with the the path/filename of the file that was executed as the first argument. Ideally it is the same as executing it from the command line like:
C:\your\application.exe "C:\The\Path\To\my.file"
Now as suggested above, you would then need to use sys.argv to to obtain the arguments passed to your application, in this case C:\Path\To\my.file would be the first argument. Simply put, sys.argv is a list of arguments passed to the application; in this case the first entry sys.argv[0] will always be the path to your application, and as mentioned above, sys.argv[1] would be the path to your custom file.
Example:
import sys
myFile = sys.argv[1]
f = file(myFile, "r")
contents = f.read()
f.close()
Then you will be able to pass the variable contents to your dialog to do whatever with.

Related

how to call a def in python?

I made this small program :
I wanna know how to automatically call it, so that when I open the .py it shows up immediatly.
Please understand that I am a beginner in Python.
The right way to do this is to add the following statement in the end of the file:
if __name__ == "__main__":
table_par_7()
Explanation
This will ensure that if you open the file directly (and thus makes it the main file), the function will run, but if another python file imports this file (thus this file isn't the main one), it wont run.
You can call it like this:
# Add this lines at the end of your code
table_par_7()
If you mean:- (1) When you will run the .py file, how to call it. Then the answer is, you will have to write the name of function and press ENTER to execute it.
(2) When you will open the .py file from any folder, is it possible to print final result. The the answer is a big NO. This is because using def in any program is just a keyword to create function. It do not have any property by which it will execute by its own. It must be called by the system which is known as system call.

How do I invoke a text editor from a command line program like git does?

Some git commands, git commit for example, invoke a command-line based text editor (such as vim or nano, or other) pre-filled with some values and, after the user saves and exists, do something with the saved file.
How should I proceed to add this functionality to a Python similar command-line program, at Linux?
Please don't stop yourself for giving an answer if it does not use Python, I will be pretty satisfied with a generic abstract answer, or an answer as code in another language.
The solution will depend on what editor you have, which environment variable the editor might possibly be found in and if the editor takes any command line parameters.
This is a simple solution that works on windows without any environment variables or command line arguments to the editor. Modify as is needed.
import subprocess
import os.path
def start_editor(editor,file_name):
if not os.path.isfile(file_name): # If file doesn't exist, create it
with open(file_name,'w'):
pass
command_line=editor+' '+file_name # Add any desired command line args
p = subprocess.Popen(command_line)
p.wait()
file_name='test.txt' # Probably known from elsewhere
editor='notepad.exe' # Read from environment variable if desired
start_editor(editor,file_name)
with open(file_name,'r') as f: # Do something with the file, just an example here
for line in f:
print line

Can't access temporary files created with tempfile

I am using tempfile.NamedTemporaryFile() to store some text until the program ends. On Unix is working without any issues but on Windows the file returned isn't accessible for reading or writing: python gives Errno 13. The only way is to set delete=False and manually delete the file with os.remove(). Why?
This causes the IOError because the file can be opened only once after it is created.
The reason is because NamedTemporaryFile creates the file with FILE_SHARE_DELETE flag on Windows. On Windows when a file has been created/opened with specific share flag all subsequent open operations have to pass this share flag. It's not the case with Python's open function which does not pass FILE_SHARE_DELETE flag. See my answer on How to create a temporary file that can be read by a subprocess? question for more details and a workaround.
Take a look: http://docs.python.org/2/library/tempfile.html
tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed.
Thanks to #Rnhmjoj here is a working solution:
file = NamedTemporaryFile(delete=False)
file.close()
You have to keep the file with the delete-flag and then close it after creation. This way, Windows will unlock the file and you can do stuff with it!

Open specific file type with Python script?

How can I make a Python script to be a specific file type's (e.g., *.foo) default application? As in, when I double click the file in the Finder / Explorer I want the file to open in the Python script.
Is this possible to do in Win and/or OS X? The application is a PySide app if that matters.
Mac OS X
On Mac OS X you can use Automator to create an application that calls your python app and passes the input file path as a string argument. In the application workflow wizard, add action "Run Shell Script", select Pass input: as as arguments, and in the text box add:
python /path/to/my/app/myapp.py "$#"
The "$#" passes along whatever arguments were in the input (aka the selected file) as strings. As long as your script is set up to deal with the input (sys.argv) as a list of strings (the first one being the python app path), then it will work.
When you save that Automator workflow, it is treated by OS X like any other app, and you can set that app as the default for files of type "*.foo". To associate "*.foo" with that app, right click a .foo file, Get Info, Open with: Other..., choose the app you created in Automator, then click the Change All... button.
Windows
A similar but hopefully less-involved approach might work in Windows. You could probably create a batch file (.bat) with the following:
python C:\path\to\my\app\myapp.py %*
The %* expands to all arguments.
As long as you can associate a file extension with that batch file, then you could do that, and that's your solution. However, I haven't tried this Windows solution, so take it with a grain of salt. The Mac solution, on the other hand, I have tested.
By example, here's a universal solution I wrote for:
1) opening a Windows desktop link (*.URL) that's been copied to a Linux box.
Or
2) opening a Linux .Desktop link that's been copied to a Windows box.
Here's the Python script that handles both cases:
# UseDesktopLink.py
import sys
import webbrowser
script, filename = sys.argv
file_object = open(filename,'r')
for line in file_object:
if line[0:4]=="URL=":
url=line[4:]
webbrowser.open_new(url)
file_object.close()
On Windows, use Scott H's method (via a bat file) to handle the association.
On Linux, right-click a Windows URL file. Choose Properties, and Open With. Click Add to add a new application. Then at the bottom of the "Add Application" window, click "Use a custom command". Then browse to the UseDesktopLink.py file and click Open. But before you click Add, in the textbox below "Use a custom command", put "python " before the filename (without the quotes). Then click Add and Close.
Hope that helps.
Find any file of type foo
right-click -> Get Info or Click on the file icon,then click Get info or click on the file and hit Command+I
In the Open With pane that shows up, select the path to the python binary
Once selected, You can click the change All button
It'll ask for confirmation, just say continue
I found this old question while looking for an answer myself, and I thought I would share my solution. I used a simple c program to direct the arguments to a python script, allowing the python script to stay a script instead of needing to compile it to make things work. Here is my c program:
int main(int argc, char *argv[]){
char cmd[0xFF];
// For me, argv[1] is the location of the file that is being opened. I'm not sure if this is different on other OSes
snprintf(cmd,sizeof cmd,"python YOUR_PYTHON_SCRIPT_HERE.py -a %s", argv[1]);
system(cmd);
return 0;
}
I then compiled the c program and set that as the default application for the file extension.
Then, in the python script YOUR_PYTHON_SCRIPT_HERE.py, I receive the argument like this:
import sys
assert len(sys.argv) > 2 # Breaks if you call the script without the arguments
theFile = " ".join(sys.argv[2:]) # What the c program gives us
print(theFile) # Print it out to prove that it works
theFile will contain the location of the file that is being opened
Get the contents of the file by using:
with open(theFile,"r") as f:
fileContents = f.read()
On Windows:
Right click the file (I used a .docx file for this example)
Select Open with...
From the applications list, select python
Optional: Select the Always use the selected program to open this kind of file.
Note: this will run the contents of the .docx file in context of the python shell. It will immediately close once it is finished evaluating the contents of the file. If you'd like to edit the file in a word processor, perhaps you should download notepad++, and select that application as the default.

Recognizing a file

I have no idea how this works or if it is even possible but what I want to do is for example create a file type (lets imagine .test (in which a random file name would be random.test)). Now before I continue, its obviously easy to do this using for example:
filename = "random.test"
file = open(filename, 'w')
file.write("some text here")
But now what I would like to know is if it is possible to write the file .test so if I set it to open with a wxPython program (directly (running the "random.test" from the desktop)), it recognizes it and for example opens up a Message Dialog automatically.
How this works varies by operating system, but, AFAIK, the general rule is that if you register your application with the operating system as recognizing that file type, then clicking on one or more files of that type causes the operating system to invoke your program with the names of the files as parameters, so your program will correctly handle the file opening if it has a commandline invocation of the following form:
program_name [options] <file1> [<file2> ... <fileN>]
In terms of identifying what file types your program can accept... on Mac OS X, this is done by listing the file types in the application bundle's "Info.plist" file in a dictionary with key CFBundleDocumentTypes. It is up to the user to perform the association, but the information in "Info.plist" determines which applications are considered candidates for registration. On Windows, you need to edit the registry to associate the program with the file type, you can also edit the registry to add "verbs" (right-click menu items) for your program.

Categories

Resources