我有一个 bash 脚本,我在其中调用了一个 python 脚本:
#!/bin/bash
python myscript.py
在 python 脚本中,我使用 selenium 包进行抓取:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
print('starting')
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
browser = webdriver.Chrome("/chromedriver",chrome_options=chrome_options)
url = "https://example.com"
browser.get(url)
...
我想运行 bash 脚本并将输出输出到控制台和日志文件:
./bash_script.sh 2>&1 | tee log.txt
我的问题是,尽管 python 脚本确实在运行,但此命令从不打印预期的消息“starting”(或 python 脚本中的任何其他 print)。
但是:
- 如果我删除
browser.get(url)命令,它会起作用 - 如果我直接调用 python 脚本(而不是通过 bash 脚本), 有用
- 如果我不重定向输出而只是调用
./bash_script.sh,它 作品
所以看起来 bash 重定向和这行特定代码 browser.get(url)
知道为什么以及如何解决这个问题吗?
请您参考如下方法:
缓冲问题?当您的 python 脚本完成时,根本没有输出?
如果是缓冲问题,stdbuf 可以提供帮助:
stdbuf -oL ./bash_script.sh 2>&1 | tee log.txt
