0

I have a python script: my_script.py that I want to call from another script main.py in a different directory.

I am doing this like so:

/home/path/to/my/main/script/main.py

import subprocess

def call_script():
    path_to_python = '/home/path/to/another/script/my_script.py'
    subprocess.call(["python", path_to_python])

/home/path/to/another/script/my_script.py

do_some_work('log_files/logs.log')

I get the following error:

File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/home/path/to/my/main/script/log_files/logs.log'

I see that the script getting called is using the path from the original scripts location as its base path.
How can I get the my_script.py to use its own path? I do not want to open a new shell.

2 Answers 2

1

Do an os.chdir() inside your my_script.py

CWD (the current working directory) in inherited from the parent process. So, since you are running your script from the location of the main script, the CWD for your child process is still set to /path/to/main.py

If you do a os.chdir('/path/to/my_script.py') your CWD is changed to the directory of my_script.py.

Or, equivalently, you can use an absolute path to the log file in your script as well.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to pass this in as a paramater when I call subprocess.call() ? as my_script.py is called from other scripts also (From within its same directory)
Since you know the absolute path to your script in main, you can pass that to your script itself. Then do some path manipulation to get the basepath.
I passed in cwd='/home/path/to/another/script/' to subprocess.call and now my other script executes correctly.
I see that the shell now changes and stays at the directory I passed in as 'cwd'. Is there a way I can spawn the other script as a new stand alone process?
Not sure I understand, the cwd should only change for the Subprocess. Is that not happening?
1

use the cwd function parameter:

path_to_python = '/home/path/to/another/script/my_script.py'
subprocess.call("python", cwd=path_to_python)

more info on the docs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.