簡體   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