繁体   English   中英

为什么无论有没有shell = True,subprocess.call(['python',argsStr])都会失败?

[英]Why does subprocess.call(['python', argsStr]) fail both with or without shell=True?

因此,我有一个旧脚本ts ,我需要使用几个字符串参数在循环中调用:

#User supplied
ts = '/d1/user/script.py'
adir = '/d1/user/adir'
mfile = '/d1/user/script.nc'
outdir = '/d1/user/park/'

metens = glob.glob(adir + '/*.nc')  #reads all files

for count, value in enumerate(metens):
    runcom = [ts, mfile, metens[count], outdir + os.path.basename(metens[count])]   
    runcom = " ".join(runcom) #This creates a string of CL arguments
    subprocess.call(['python2.7', runcom], shell=True) 

现在,当我运行它时,它将调用python2.7并打开Python Shell,而不是将其作为python2.7 runcom运行。

如何使它作为脚本运行而不是打开外壳?

如何修复

args = ['script.py', 'first argument', 'second argument']
subprocess.call(['python2.7'] + args)
  • 不要使用shell=True
  • 将每个参数作为单独的列表项传递; 不要将它们串联成字符串。

为什么失败(使用shell=True

我们来看一个简单的例子:

args = [ 'script.py', 'first argument' 'second argument' ]
args_str = ' '.join(args)
subprocess.call(['python2.7', args_str], shell=True)

实际上是做什么的?

# the above is the same as running this at a shell
sh -c python2.7 'script.py first argument second argument'

实际上是做什么的? 它运行的python2.7完全没有参数(因为参数列表被解释为sh -c实例的$0 ,但是在列表的第一个元素中传递的脚本仅包含字符串python2.7而不会查看完全是$0 )。


为什么失败(没有shell=True

我们来看一个简单的例子:

args = [ 'script.py', 'first argument' 'second argument' ]
args_str = ' '.join(args)
subprocess.call(['python2.7', args_str])

实际上是做什么的?

# the above is the same as running this at a shell
python2.7 'script.py first argument second argument'

...并且即使当前目录中有一个script.py这又怎么办?

python2.7: can't open file 'script.py first argument second argument': [Errno 2] No such file or directory

为什么会这样呢? 因为您将参数作为脚本文件名的一部分,所以不存在将这些参数值作为其名称一部分的文件名。

链接的答案不能直接回答我的问题

for count, value in enumerate(metens):
    subprocess.call(['python2.7', ts, mfile, metens[count], outdir + os.path.basename(metens[count]]) 

如果在子进程内部构建了runco​​m,则可以运行。 但是,如果在外部构造它,则会出现无文件错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM