【问题标题】:Running two python scripts simultaneously from batch file, using anaconda, not working使用anaconda从批处理文件同时运行两个python脚本,不起作用
【发布时间】:2020-11-16 08:03:30
【问题描述】:

因此,根据thisthis,要同时运行两个python 脚本,我应该从一个批处理文件中运行它们,并用& 分隔。

但是,这在一个简单的示例中似乎不起作用。

我目前正在尝试这个:

test1.py

import time
for i in range(5):
    time.sleep(1)
    print("Printing, test1:"+str(i))

test2.py

import time
for i in range(5):
    time.sleep(2)
    print("Printing, test2:"+str(i))

批处理文件

call "C:\Users\Username\Anaconda3\Scripts\activate.bat"
"C:\Users\Username\Anaconda3\python.exe" "C:\Users\Python\Documents\Python\Test\test1.py" &
"C:\Users\Username\Anaconda3\python.exe" "C:\Users\Python\Documents\Python\Test\test2.py" &

我希望看到混合的结果,但是,结果如下:

很明显,脚本 2 在脚本 1 之后运行。

有什么想法吗?

谢谢!

【问题讨论】:

  • 您的两个链接问题显然都在谈论 Unix shell 脚本,不是 Windows 批处理文件。
  • 哇.. 我没听懂。谢谢!有什么办法在 Windows 上做到这一点?
  • & 在批处理文件中连接命令,因此第二个在第一个完成后运行。运行两者都使用start “” “first command”start “” “second command"。注意第一对引号是窗口标题。请参阅start /? 了解更多信息

标签: python batch-file


【解决方案1】:

感谢@jasonharper 指出我发现的两个解决方案是 Unix 特有的,不是 Windows(尽管我搜索过 Windows),我能够找到 this 其他帖子, 适用于 Windows。

稍微适应 conda,我就可以让机器人脚本同时运行,如下所示:

批处理文件

call "C:\Users\Username\Anaconda3\Scripts\activate.bat"
start python "C:\Users\Username\Documents\Python\Test\test1.py" &
start python "C:\Users\Username\Documents\Python\Test\test2.py" &

结果很酷。两个 python 窗口同时运行:

谢谢大家!

【讨论】:

    【解决方案2】:

    使用python的多处理或线程模块

    import time
    import threading
    def test1():
        for i in range(5):
            time.sleep(1)
             print("Printing, test1:"+str(i))
    def test2():
        for i in range(5):
            time.sleep(2)
            print("Printing, test2:"+str(i))
    x = threading.Thread(target=test1)
    t = threading.Thread(target=test2)
    x.start()
    t.start()
    

    【讨论】:

    • 谢谢。但是,这对我不起作用。我仍然得到一个接一个的结果。我从批处理文件和 PyCharm 都试过了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多