2

I have compiled my python program with cx_Freeze with the lines

import sys
print(sys.argv[0])

to get the name of the extension file that runs my application. I want to be able to double click on a file named Foo.bas and then my compiled executable starts and it can open the file and read its contents. So I want to get the extension path and file name and read its contents like this

with open(file, "r") as f:
    data = f.read()
# do things with contents

where file would be the extension path and name

So how would I do that?

jpeg
  • 2,372
  • 4
  • 18
  • 31
Dextron
  • 598
  • 7
  • 24

1 Answers1

1

sys.argv[0] gives you the first entry of the command used to run your script, which is the script name itself. If you double-click on a file whose extension is associated with your script or frozen application, the name of this file becomes the second argument of the command, which is available through sys.argv[1]. See for example sys.argv[1] meaning in script.

So try with the following script:

import os
import sys
if len(sys.argv) > 1:
    filename = sys.argv[1]
    print('Trying with', filename)
    if os.path.isfile(filename):
        with open(filename, 'r') as f:
            data = f.read()
            # do things with contents
else:
    print('No arguments provided.')
input('Press Enter to end')

This works both as unfrozen script and as executable frozen with cx_Freeze. On Windows you can drag and drop your Foo.bas file onto the icon of your script or executable, or right-click on Foo.bas, chose Open with and select your script or executable as application.

jpeg
  • 2,372
  • 4
  • 18
  • 31
  • I only figured that out byt playing around with the command and recieving the file name and Foo.bas file name. I was going to try it until i checked the post again. Thanks – Dextron Feb 12 '19 at 08:52