【问题标题】:Using Python to run a sourced script, cd, and then run a command within the SAME shell使用 Python 运行源脚本 cd,然后在 SAME shell 中运行命令
【发布时间】:2018-10-19 18:30:48
【问题描述】:

如何在同一个 shell 中运行源化 bash 脚本,然后更改目录,然后运行命令(使用 python)?这甚至可能吗?

我的尝试:

subprocess.check_call(["env -i bash -c 'source ./init-build ARG'", "cd ../myDir", "bitbake myBoard"], shell =True)

【问题讨论】:

  • 将 check_call 更改为 check_output。 check_call 退出而不等待后代进程,而 check output 等待直到读取所有输出。

标签: python bash subprocess


【解决方案1】:

我会为你做这个,但我需要查看绝对路径。这是一个例子

subprocess.check_call(["""/usr/bin/env bash -c "cd /home/x/y/tools && source /home/x/y/venv/bin/activate && python asdf.py"  >> /tmp/asdf.txt 2>&1"""], shell=True)

【讨论】:

  • 成功了!谢谢!你能解释一下“>> /tmp/asdf.txt 2>&1”部分吗?
  • 您可以出于您的目的取出>> /tmp/asdf.txt 2>&1。我从我的 crontab 中获取了它。它的作用是 cd 到目录、获取 virtualenv 和 python 脚本。我想将输出保存到文件中。 >> 表示追加。 2 是 stderr 2>&1 是 1 的快捷方式。所以它可以重写为: >> 1>/tmp/asdf.txt 2>/tmp/asdf.txt (获取输出和std err输出并保存到/ tmp/asdf.txt.
猜你喜欢
  • 2013-08-21
  • 2012-04-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 2013-07-11
  • 1970-01-01
相关资源
最近更新 更多