1

I try to write some batch that can autorun my python scripts.Here is my batch file:

@echo off
:: do something here
pythonw xx.py
rem run python script in the backgroud
rem but batch stops here, doesn't run the rest code
:: do something else again

So how can I fix this. Any help will be appreciated!
Related question:
Running Python Script as a Windows background process

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Spaceship222
  • 759
  • 10
  • 20
  • 2
    That `REM` has to be on its own line. – Squashman Jun 28 '18 at 18:00
  • 1
    Try running it with `@echo on` and using `python` instead of `pythonw`—that way you can see the error messages. – martineau Jun 28 '18 at 18:02
  • 2
    Does the rest of the batch run after your Python script ends? If so, I suggest you start the Python script using the Windows `start` command with its `/b` argument (but avoid its `/wait` argument). – martineau Jun 28 '18 at 18:08
  • @martineau I didn’t test it, because xx.py acts as server listening at the background. When running ‘pythonw xx.py’, batch will hang there and not continue running. – Spaceship222 Jun 28 '18 at 18:15
  • 1
    Spaceship222: OK, well try the [`start`](https://ss64.com/nt/start.html) command I recommend, which should allow the server to keep running _and_ allow the rest of the batch file to keep running as well. – martineau Jun 28 '18 at 18:20
  • 1
    @martineau It works! Thanks very much! – Spaceship222 Jun 28 '18 at 18:31
  • 1
    Spaceship222: That's very good to hear. Note also, as explained in this [answer](https://stackoverflow.com/a/30313091/355230) to a related question, that when using `pythonw.exe`, "**Unhandled exceptions** cause the script to **abort silently**" which could make debugging problems more difficult (which is why I originally suggested using plain `python` so you could see any errors that might be occurring). – martineau Jun 28 '18 at 18:39
  • 1
    Please don't add the solution to the question; post an answer instead (perhaps wait a bit and give @martineau some time to post his comments as a real answer, which you can later [accept](https://stackoverflow.com/help/accepted-answer))... – aschipfl Jun 28 '18 at 18:56

1 Answers1

2

You should be able to get the batch file to keep running by executing the Python script using Windows start command.

So in your case the batch file should look something like:

@echo off
:: do something here
rem Run python script in the backgroud
start "title" /b pythonw xx.py
:: do some more stuff...
martineau
  • 119,623
  • 25
  • 170
  • 301