【问题标题】:Python subprocess Popen passing argumentsPython子进程Popen传递参数
【发布时间】:2014-05-03 12:25:11
【问题描述】:

我试图从我的 python 调用一个带有参数的 shell 脚本,但参数没有被传递

我的 Shellscript:

echo "Inside shell"
echo $0
echo $1
cd $1
pwd
for file in *.csv
do
  split -l 50000 -d -a 4  "$file" "$file"
done
echo "Outside shell"

shell=True

this_dir = os.path.dirname(os.path.abspath(__file__))
cmd = [os.path.join(this_dir,'split.sh'),fileslocation]
print 'cmd = ', cmd
process = subprocess.Popen(cmd,shell=True)

参数没有正确传递...

移除 Shell=True

cmd =  ['/opt/sw/p3/src/PricesPaidAPI/split.sh', '../cookedData']
Traceback (most recent call last):
  File "csv_rename.py", line 23, in <module>
    process = subprocess.Popen(cmd)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error

【问题讨论】:

  • Python raise child_exception OSError: [Errno 8] Exec format error 的可能重复项(您的 shell 脚本缺少 shebang...)
  • @Wooble 我不会说您提供的链接回答了这个问题。它清楚地表明 OP 必须重新编译他的程序,而且它不是脚本。 Shebang 只是一个未经证实的建议。虽然可能是对的。
  • 接受的答案给出了导致 OP 错误的 2 种可能性,从他在问题中粘贴的脚本中,您可以看到没有 shebang 行。
  • @Wooble 再次。这是一个未经证实的建议,不是吗?你确定它有效吗?看看这里stackoverflow.com/questions/15072508/… 有人有一个shebang,似乎它不起作用。必须使用shell=True
  • 我确信它适用于这个问题的 OP,是的。 shell=True 是个坏主意,其他问题的 OP 可以用另一种方式解决它。

标签: python shell


【解决方案1】:

好的,我不知道这是否应该是骗子(根据 cmets)。但事实是shebang有所帮助。这是确认。

popen_test.py:

import subprocess
subprocess.Popen(["./dummy.sh", "test"])

noshebang.sh:

echo "Echoing: $1"

此结果为OSError: [Errno 8] Exec format error。这是因为操作系统希望文件是可执行的(duh)。但是,第一行中的#! - shebang 是系统的特殊标记,表示该文件应在其指定的shell 环境中执行。所以它可以被视为一个可执行文件,即使它不是。所以:

shebang.sh:

#!/bin/sh

echo "Echoing: $1"

工作。

本质上和python的shell=True一样。只是系统会照顾它。 IMO 用这种方法注入随机代码有点困难。所以我建议去。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多