Reputation: 75
During the course of my python program, I have generated the following string
"D:\something_else.py"
Lets say there are other resources in D: that something_else.py requires.
How would I go about running something_else.py from my code, which let's say is being run from C:\Users\Someone\Desktop?
Right now I'm using the following:
from subprocess import call
call(["python",pythloc])
This gives me an error as it's able to find only something_else.py and is unable to find the other resources that something_else.py needs which are in the same folder as something_else.py
Upvotes: 3
Views: 167
Reputation: 1155
If you can have the mentioned folder as part of the project itself, you can turn that into python package, simply by adding an empty file in the folder named __init__.py
If it is on some other path like "D:\some_directory\", which has something_else.py
along with other dependencies, do this along with your import statements:
sys.path.append(r"D:\some_directory\")
from something_else import some_useful_function, some_useful_class
It will add the mentioned directory to your sys.path
, and then you can import anything from python files kept there, and just call the functions as usual.
If you are using any IDE like PyCharm, it may still show you unresolved errors
for the 2nd line, as part of import checks. But the code will simply work when you run it.
It's almost never a good idea to call a python script from other(python something.py
), when you can just import and call functions, with a better control & error checking.
Upvotes: 2
Reputation: 1223
Besides the fact that you need to be careful with "\" and instead of :
locationDir="D:\something_else.py"
prepend your string with r:
locationDir=r"D:\something_else.py"
you can simply set the PYTHONPATH environment variable to point to the directory in which sit the other modules.
See here for additional informations :
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH
Upvotes: 3