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



Important Note:
If your script (a.py) contains a continuous loop waiting for user input
(as shown in your code),
subprocess.run() will not be able to handle it properly
because it doesn't support interactive input.
If you need to execute a script that requires user input,
you might want to use subprocess.Popen() instead,
as it allows more control over the standard input/output.

# Run the Python script a.py
result = subprocess.run(['python3', 'a.py'], capture_output=True, text=True)

# Print the output from the script
print(result.stdout)
print(result.stderr)

# a.py:
while True: print("AAA") print("BBB") print("CCC") user_input = input("Enter something (or 'exit' to quit): ") if user_input.strip() == 'exit': break print(f"You entered: {user_input}")