0

Lets say I have a symlink in directory A which points to a python file in directory B. When I execute the symlink, the python file in directory B successfully executes (it also uses other python files in its directory). However, there are a lot of issues with using symlinks in terms of operating systems so I would like to emulate this using plain python.

Here is what I have so far.

File in directory A:

import os
import sys
sys.path.append("DirectoryB") # File_B is importable now
os.chdir("DirectoryB") # Change dir so File_B's imports work
import File_B # Run File_B

So now when the directory A file is run - file B will successfully be run as if the file in directory A was a symlink.

Is there anything wrong/missing with this approach? And is there a way to do it better?

Ogen
  • 6,499
  • 7
  • 58
  • 124

1 Answers1

0

Your question is very similar to invoking a python script from another one which has already two answers in Run a python script from another python script, passing in args and What is the best way to call a Python script from another Python script? Your fragment is OK, but there may be some differences from the symlink. E.g. If File_B uses the classic idiom if __name__ == '__main__':, then the 'if' would not be True with the import and you should invoke the code in that section directly.

To invoke File_B you can use ececfile("/path_to/File_B") to maintain the same arguments or os.system("/path_to/File_B %s" % ' '.join(arglist)) if you need to change the arguments.

If you prefer to avoid the OS and keep it in Python, check if you have to call a function or add some code after the import (e.g. if File_B has a if __name__ == '__main__':). And in https://stackoverflow.com/a/3781960/3547046 there are some suggestions to preserve the arguments.

marco
  • 488
  • 4
  • 9
  • My File_B doesn't use that idiom. Also, I think with just the import statement the stdin args would be preserved? – Ogen May 28 '18 at 04:05