如何使用子进程指定文件位置?

How can I specify file locations using subprocess?

我正在对 运行 多个 python 脚本使用子进程:

import subprocess

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

如何指定脚本文件位置?

试试这个:

# 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')

对于更复杂的情况:

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,
)