9.12.2024

Python3的py script呼叫其它的py script並執行

Ref: https://stackoverflow.com/questions/1186789/how-to-call-a-script-from-another-script

File test1.py:

print "test1.py"

File service.py:

import subprocess

subprocess.call("test1.py", shell=True)

The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.

Documentation: Python 2Python 3


(當呼叫的py script是跟使用者有輸入輸出的互動時,

subprocess.call可以使得跟直接執行另一個py一樣)


Ref: https://stackoverflow.com/questions/51928521/eoferror-when-starting-with-subproccess


EOFError when starting with subproccess


You are using subprocess.Popen which is a by default non blocking, piece of code, hence You program cursor moves rather than waiting for the input from the user. But what you need is a code which is blocking your program cursor. subprocess.call exactly does it. It would be waiting for the other command to execute completely.

You need to use subprocess.call to solve your problem. Just change your script2 file with this

import subprocess
p = subprocess.call(["python", "abca.py"])

You can read more about the difference between subprocess.Popen and subprocess.call in this answer. Which describes when to use which command and the difference between them

沒有留言:

張貼留言