1

I am very disappointed that after looking for several hours, I have still not found an answer to: - Make a python script that opens another python script ?

Mabye I don't know how to search for stuff, but I am usually good at finding solutions online.

Any help would be gladly appreciated!

Here's my code:

import subprocess    
subprocess.Popen(['C:\Users\user\Documents\run.py'])

Here is the python file called "run.py"

print('Hello World!')

Thanks!

  • 1
    if you have access to that python script, why don't you just import the content from it? – Stargazer Jan 03 '20 at 09:33
  • Do you want just to open `run.py` as a text file? Or, do you want to execute `run.py`? – nekketsuuu Jan 03 '20 at 09:34
  • What about this? [https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script](https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script) – weAreStarsDust Jan 03 '20 at 09:34
  • I want a script to run several scripts in subfolders automatically so I don't have to do it myself :) – Extranoisy88 Jan 03 '20 at 11:58

4 Answers4

4

You can use the call library, it's pretty easy:

from subprocess import call

call(["python", "your_file.py"])
Proteeti Prova
  • 1,079
  • 4
  • 25
  • 49
2

This is how I will go about it. Suppose you have two files: Main.py and run.py and will want Main.py to open and run this file run.py:

  1. this is the content of Main.py : it calls run.py through import (run.py file needs to be in the same folder)

import run

  1. this is your run.py

print('Hello World!')

Then you can run Main.py by calling python Main.py

the output will be : Hello World!

Let me know if it works.

MEdwin
  • 2,940
  • 1
  • 14
  • 27
1

Try this:

your_cmd = "python3 path/to/file/run.py"
p = subprocess.Popen("exec " + your_cmd, stdout=subprocess.PIPE, shell=True)
Shweta Chandel
  • 887
  • 7
  • 17
0

i find this to work and it looks clearer:

import subprocess
import pathlib


path_to_file=pathlib.Path(__file__).parent.resolve()
script_path=f'{path_to_file}/your_script.py'

subprocess.run(['python',script_path])
KZiovas
  • 3,491
  • 3
  • 26
  • 47