Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python程序中使用shell脚本?_Python_Csh_Os.system - Fatal编程技术网

如何在python程序中使用shell脚本?

如何在python程序中使用shell脚本?,python,csh,os.system,Python,Csh,Os.system,我想在一个python程序中使用一个C-shell脚本,它使用两个参数 os.system("recall 20170121 ../E725.txt xy 1") 但是我想将它用于堆栈,所以声明了如下所示的变量,但是当我在脚本中调用它们时,它给出了一个错误,即输入文件不存在。如何调用变量 date_ID=(filename[17:25]) fullpath = '../%s' % (filename) os.system("import_S1_TOPS_modified $date_ID $f

我想在一个python程序中使用一个C-shell脚本,它使用两个参数

os.system("recall 20170121 ../E725.txt xy 1")
但是我想将它用于堆栈,所以声明了如下所示的变量,但是当我在脚本中调用它们时,它给出了一个错误,即输入文件不存在。如何调用变量

date_ID=(filename[17:25])
fullpath = '../%s' % (filename)
os.system("import_S1_TOPS_modified $date_ID $fullpath vv 1")

shell不知道Python变量,因为它是一个完全不同的系统。因此,您不能使用shell的变量替换机制$date\u ID。相反,您必须将它们作为Python字符串传递:

os.system("import_S1_TOPS_modified %s %s vv 1" % (date_ID, fullpath))
请注意,这段代码有一个严重的问题:如果有人给出;rm-rf/;作为文件名?该命令现在看起来像:

import_S1_TOPS_modified 20181021; rm -rf /; vv 1
这将删除所有内容

这就是为什么使用subprocess是一个更好的主意,它根本不使用shell,也不容易出现这种问题:

subprocess.call(['import_S1_TOPS_modified', date_ID, fullpath, 'vv', '1'])
如果必须使用shell,请使用shlex.quote并添加shell=True:

subprocess.call("import_S1_TOPS_modified %s %s vv 1" % (
    shlex.quote(date_ID), shlex.quote(fullpath)),
    shell=True)