I want to use a C-shell script within a python program, which works with two arguments.
os.system("recall 20170121 ../E725.txt xy 1")
But I want to use it for a stack, so declared the variables like below, but when I call them within the script it gives an error, that the input file doesn't exist. How can I call the variables?
date_ID=(filename[17:25])
fullpath = '../%s' % (filename)
os.system("import_S1_TOPS_modified $date_ID $fullpath vv 1")
The shell doesn't know about the Python variables, as it's a completely different system. So you can't use the shell's variable substitution mechanism ( $date_ID
). Instead, you'll have to pass them as a Python string:
os.system("import_S1_TOPS_modified %s %s vv 1" % (date_ID, fullpath))
Note that this code has a serious problem: what if someone gives ; rm -rf /;
; rm -rf /;
as filename
? the command will now look like:
import_S1_TOPS_modified 20181021; rm -rf /; vv 1
Which will delete everything.
This is why it is a better idea to use subprocess
, which will not use the shell at all, and isn't vulnerable to this sort of problem:
subprocess.call(['import_S1_TOPS_modified', date_ID, fullpath, 'vv', '1'])
If you must use the shell, then use shlex.quote()
and add shell=True
:
subprocess.call("import_S1_TOPS_modified %s %s vv 1" % (
shlex.quote(date_ID), shlex.quote(fullpath)),
shell=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.