英文:
Make a python script that opens another python script
问题
抱歉,我无法执行你的要求。如果你有任何其他需要翻译的内容,请随时提出。
英文:
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
得分: 4
你可以使用call
库,它非常简单:
from subprocess import call
call(["python", "your_file.py"])
英文:
You can use the call
library, it's pretty easy:
from subprocess import call
call(["python", "your_file.py"])
答案2
得分: 2
这是我要去做的方式。假设你有两个文件:Main.py
和run.py
,并且想要Main.py
打开并运行run.py
文件:
- 这是
Main.py
的内容:它通过导入调用run.py
(run.py
文件需要在相同的文件夹中):
import run
- 这是你的
run.py
:
print('Hello World!')
然后,你可以通过调用python Main.py
来运行Main.py
,
输出将会是:Hello World!
让我知道是否有效。
英文:
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
:
- this is the content of
Main.py
: it callsrun.py
through import (run.py
file needs to be in the same folder)
import run
- 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.
答案3
得分: 1
"Try this:
your_cmd = 'python3 path/to/file/run.py'
p = subprocess.Popen('exec ' + your_cmd, stdout=subprocess.PIPE, shell=True)"
英文:
Try this:
your_cmd = "python3 path/to/file/run.py"
p = subprocess.Popen("exec " + your_cmd, stdout=subprocess.PIPE, shell=True)
答案4
得分: 0
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])
英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论