Python subprocess Popen 传递参数

1 投票
1 回答
620 浏览
提问于 2025-04-18 05:14

我想在我的Python代码里调用一个shell脚本,并且传递一个参数,但这个参数没有被正确传递。

我的Shell脚本是:

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

1 个回答

0

好吧,我不知道这是不是重复的问题(根据评论来看)。但有一点是事实,shebang确实有帮助。这里有个确认。

popen_test.py:

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

noshebang.sh:

echo "Echoing: $1"

这样会导致 OSError: [Errno 8] Exec format error 的错误。这是因为操作系统期待这个文件是可以执行的(显而易见)。但是,第一行的 #! - shebang 是一个特殊的标记,告诉系统这个文件应该在它指定的shell环境中执行。所以即使这个文件本身不是可执行的,它也可以被当作可执行文件来处理。因此:

shebang.sh:

#!/bin/sh

echo "Echoing: $1"

可以正常工作。

这基本上和python中的 shell=True 是一样的。只是系统会自动处理这个问题。在我看来,用这种方式注入随机代码会稍微难一些。所以我建议使用这个方法。

撰写回答