0

We are creating a python program that executes specific macros within Polyworks based on user input into the program. Right now the code is:

roto.command.CommandExecute('MACRO EXEC("C:\\RotoWorks\\Macros\\CentrifugalCompressor")')

However this assumes that our program is always installed in C:\RotoWorks. Ideally, our app is portable. I'm sure theres a way to retrieve the filepath that Rotoworks is stored in, then just concatenate the rest of the filepath to the end. How do I do this?

RBuntu
  • 907
  • 10
  • 22
  • Possible duplicate of [How to properly determine current script directory in Python?](http://stackoverflow.com/questions/3718657/how-to-properly-determine-current-script-directory-in-python) –  Aug 15 '16 at 19:11

1 Answers1

2

You can retrieve the path from the __file__ attribute of the file. Use os.path.abspath on that attribute to retrieve the absolute path of the file and then os.path.dirname to retrieve the containing directory:

import os

file_directory = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(file_directory, other_path) # join directory to an inner path
roto.command.CommandExecute('MACRO EXEC({})'.format(path))

Use os.path.dirname recursively to move out as many directories as you want.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • I used and it worked when running as a python script. But when I packaged it into an executable using py2exe, it says '__file__ is not defined'. How do I avoid this? – RBuntu Aug 15 '16 at 19:25
  • @RBuntu That would require a slightly different approach. This: [How do I get the path of the current executed file in python?](http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python) – Moses Koledoye Aug 15 '16 at 19:29
  • Thanks! I'll check it out – RBuntu Aug 15 '16 at 19:58