【问题标题】:/bin/sh: 1: Syntax error: word unexpected - Using os.system() from Python/bin/sh: 1: 语法错误:单词意外 - 使用 Python 中的 os.system()
【发布时间】:2019-04-28 23:40:03
【问题描述】:

我正在尝试从 python 执行 shell 命令。这是命令:

(flock -n 200 || (echo no; exit 1) && (echo yes; cat /home/user/Desktop/instructions.json; >/home/user/Desktop/instructions.json)) 200>>/home/user/Desktop/instructions.json

我试过 os.system() 或 subprocess.call();但是我总是有同样的错误:

/bin/sh: 1: Syntax error: word unexpected

我认为问题是由括号引起的,但我不确定。

感谢 cat ,我正在尝试读取文件,然后如果它没有被锁定,则删除它的内容,否则只回显 no 并退出。

此命令在 shell 中工作。

【问题讨论】:

  • 当你说“[t]他的命令在 shell 中工作”时,你的意思是你在 Bash 中运行它吗?与 sh 这样的更简单的 shell 相比,Bash 有一些扩展。如果您打开一个新终端并启动 sh (/bin/sh) 并尝试运行您的命令,那么它可以工作吗?
  • 不,它没有,抱歉写错了我的意思是当我打开一个新终端并直接粘贴它时该命令有效。
  • 那么你很可能在 Bash 中运行它。从终端运行 /bin/sh 并再次粘贴完整的命令。有用吗?
  • 我试过了,它不起作用,我有以下错误:bash: syntax error near the unexpected "flock" symbol
  • 您甚至没有展示您在 Python 中尝试的代码。请张贴。

标签: python shell subprocess os.system flock


【解决方案1】:

要在 shell 中从 python ad 执行命令,请使用 shell=true 作为参数:

subprocess.call("your command", shell=true)

this post

【讨论】:

  • 我试过了,但它不起作用。使用 shell=true 我得到 /bin/sh: 1: Syntax error: word unexpected 。当我不输入 shell=true 时,我得到“FileNotFoundError: [Errno 2] No such file or directory: '(flock -n 200 || ...”
【解决方案2】:

您似乎正在尝试在 Python 中锁定文件。

在你的情况下,你有两个机会:

  • 可以使用python函数fcntl.flock()直接锁定文件
  • 您也可以使用一个简单的脚本 sh,在开头写上#!/bin/sh

【讨论】:

  • 是的,谢谢我使用了flock函数并且它有效!无需使用shell命令!谢谢!
猜你喜欢
  • 2016-10-18
  • 2016-05-30
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2016-04-18
  • 2020-11-23
  • 2017-07-03
  • 2015-05-12
相关资源
最近更新 更多