0

I wrote a Script.py script. In this script I start to initialize some variables, than there are 7 classes and in the end I run a cerebro to backtest stocks:

> if __name__ == '__main__':
>     cerebro = bt.Cerebro()
>     ...
>     ...

If I run the script manually, the backtest works perfectly and I get exactly the results I want. But if I want to run this script from another Script like this:

import os
import Backtest
os.system('Backtest.py')

for this I put all the scripts in one folder and imported each script in the Runner Script. Each script works perfectly, only the Backtest.py script gives the error message

sh: Backtest.py: command not found

I also have to mention that the other scripts (which work and can also be executed by the runner script via os.system ) all contain no classes and no "if name == 'main':".

Does anybody know why this backtest.py script is not found and how I can solve this problem?

best regards

chrissi2909
  • 51
  • 2
  • 6
  • 1
    [`os.system('python Backtest.py')`](https://stackoverflow.com/questions/7974849/how-can-i-make-one-python-file-run-another) – ssp Dec 20 '20 at 12:10
  • 1
    If you have multiple python interpreters (python 2, python 3, virtual/conda envs, ...), you can use `sys.executable` to get the path of the current interpreter. `os.system(sys.executable + " Backtest.py")` would account for that. – Niklas Mertsch Dec 20 '20 at 12:16

1 Answers1

0

I think the best way to achieve what you are trying to do, given you are running a python script by invoking: another shell, another python interpreter (which not necessarily is the same you are running your script with), would be to move your main section in a main() function and then from the other script import it and call it as a normal function. So instead of sys.executable, you would have:

if __name__ == '__main__':
    Backtest.main()

os.system is a rather odd way of invoking an executable in general: please, use the subprocess module, in the future

Nicola
  • 81
  • 3
  • What does this have to do with the problem? `subprocess` is more versatile, but using `os.system` is totally fine in cases where it does exactly what is required. – Niklas Mertsch Dec 20 '20 at 12:47
  • Thank you Nicola! This solved my problem :=) I made the "if __name__ == '__main__':" Part to a main() method and than I called this method in this script. After that I could use: if __name__ == '__main__': Backtest.main() in my runner script :) And you think that I should run these scrips with subprocess incase of os.sys? best ragards! – chrissi2909 Dec 20 '20 at 14:00