Home > Software engineering >  How can I specify file locations using subprocess?
How can I specify file locations using subprocess?

Time:04-26

I am using subprocess to run multiple python scripts:

import subprocess

subprocess.run("python3 script1.py & python3 script2.py", shell=True)

How can I specify the script file locations?

CodePudding user response:

try this:

# main.py

import subprocess

subprocess.run(
    "python3 script1.py & python3 script2.py",
    cwd='my_dir',
    shell=True,
)
$ tree .      
.
├── main.py
└── my_dir
    ├── script1.py
    └── script2.py

1 directory, 3 files

$cat my_dir/script1.py
print('script1')

$cat my_dir/script2.py
print('script2')

For more complicated case:

from pathlib import Path

BASE_DIR = Path(__file__).parent

import subprocess

subprocess.run(
    "python3 script1.py & python3 script2.py",
    cwd=BASE_DIR / 'my_dir',
    shell=True,
)
  • Related