Make a python script that opens another python script

huangapple go评论67阅读模式
英文:

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.pyrun.py,并且想要Main.py打开并运行run.py文件:

  1. 这是Main.py的内容:它通过导入调用run.pyrun.py文件需要在相同的文件夹中):
import run
  1. 这是你的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:

  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.

答案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])

huangapple
  • 本文由 发表于 2020年1月3日 17:31:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定