简体   繁体   English

Python.在for循环中打开另一个程序

[英]Python. Open another program in for loop

I'm creating a program in Python and I have a problem with a for loop and opening program in this loop.我在 Python 中创建了一个程序,我在这个循环中遇到了 for 循环和打开程序的问题。 The program is supposed to run eg 5 times and it only runs once该程序应该运行 5 次,但只运行一次

import subprocess

z = int(input())

def run():
    subprocess.run('notepad.exe')

a = 0
while(a<z):
    a = a + 1
    run()

I've tried creating a function and replacing the for loop with a while loop but it doesn't work.我尝试创建一个 function 并将 for 循环替换为 while 循环,但它不起作用。 Sorry for my English对不起我的英语不好

Now it depends what you want.现在这取决于你想要什么。 subprocess.run() opens the program, and pauses the code until you close notepad. subprocess.run()打开程序,并暂停代码,直到您关闭记事本。 Then, it will re open it, and do it z many times.然后,它会重新打开它,并重复多次。

If you want to open z many instances of notepad at the same time you need to use `subprocess.Popen('notepad.exe', '-new-tab')如果你想同时打开 z 多个记事本实例,你需要使用 `subprocess.Popen('notepad.exe', '-new-tab')

From the look of the code this may or may not be an issue.从代码的外观来看,这可能是也可能不是问题。 Python doesn't know where notepad.exe is located. Python 不知道notepad.exe在哪里。 You need to add the full path of the executable file.您需要添加可执行文件的完整路径。 For example, try this:例如,试试这个:

import subprocess

z = int(input())

def run():
    subprocess.run(r'C:\WINDOWS\system32\notepad.exe') #For most people this is the location of notepad.exe

a = 0
while(a<z):
    a = a + 1
    run()

Use subprocess.Popen('notepad.exe') , this will put the process in the background.使用subprocess.Popen('notepad.exe') ,这会将进程置于后台。

subprocess.run() will wait for the exit code I think, which waits until you close the notepad. subprocess.run()将等待我认为的退出代码,它会等到您关闭记事本。

So full code is所以完整的代码是

import subprocess

z = int(input())

def run():
    subprocess.Popen('notepad.exe')

a = 0
while(a<z):
    a = a + 1
    run()

You need to do pip install AppOpener first (or however you install modules for your device).您需要先执行 pip 安装 AppOpener(或者为您的设备安装模块)。

from AppOpener import open

z = int(input('Enter the number of times to open notepad: '))

def run():
    open('notepad')
    

a = 0
while(a < z):
    a = a + 1
    run()

Additionally, for running any different apps, just change 'notepad' to the name of the app.此外,要运行任何不同的应用程序,只需将“记事本”更改为应用程序的名称即可。 (For Example: 'facebook') (例如:'facebook')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM