我想使用python来迷你bash命令
./script.sh &> /tmp/my.log &
。请注意,我不希望 python 将整个命令 ./script.sh &> /tmp/my.log &
作为 shell 直接运行,因为在将消息写入日志文件之前,我可能需要对 python 中的日志消息执行一些操作(代码未显示)。
import subprocess
import threading
import sys
log_file = sys.argv[1]
program_and_args = sys.argv[2:]
with open(log_file, 'w') as log:
process = subprocess.Popen(program_and_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, start_new_session=True)
print(f"Background process started. PID: {process.pid}")
def capture_output():
for line in process.stdout:
log.write(line)
log.flush()
process.wait()
# capture_output()
thread = threading.Thread(target=capture_output, daemon = True)
thread.start()
print("Main program continuing...")
虽然上面的python程序可以运行如下。
./main.py /tmp/my.log ./script.sh
但是
/tmp/my.log
中什么也没写。如何修复python程序,使其与bash命令具有相同的效果./script.sh &> /tmp/my.log &
你把这一切都搞得太复杂了。
process = subprocess.Popen(
program_and_args,
stdout=open(log_file, 'w'),
stderr=subprocess.STDOUT,
)
无需螺纹。无需管道。不需要
with
块。您将获得与 &
等效的行为,因为您没有调用 process.wait()
,并且您将获得与 &>log_file
(或其更可移植的等效物 >log_file 2>&1
)等效的行为,因为 stdout
直接指向该文件,并且 stderr配置为与标准输出流连接。