我正在运行一个python3脚本,它在Debian 9上执行以下代码片段:
os.environ["PA_DIR"] = "/home/myname/some_folder"
command_template = ("sudo java -Dconfig.file=$PA_DIR/google.conf "
"-jar ~/big/cromwell-42.jar run $PA_DIR/WholeGenomeGermlineSingleSample.wdl "
"-i {} -o $PA_DIR/au_options.json > FDP{}.log 2>&1")
command = command_template.format("test.json, "1")
os.system("screen -dm -S S{} bash -c '{}'".format("1", command))
PA_DIR的使用按预期工作。当我在命令行上尝试它时:
PA_DIR="/home/myname/some_folder"
screen -dm -S S1 bash -c 'sudo java -Dconfig.file=$PA_DIR/google.conf -jar ~/big/cromwell-42.jar run $PA_DIR/WholeGenomeGermlineSingleSample.wdl -i test.json -o $PA_DIR/au_options.json > FDP1.log 2>&1'
由于单引号,它不做变量替换,我不得不用双引号替换它们(它抱怨它找不到文件/google.conf)。 python运行时有什么不同? 谢谢!
分析解答
Python os.system()
调用C库的底层system
function,在POSIX系统上相当于做类似的事情。
sh -c "your_command and all its arguments"
因此命令和所有参数都已被double-quotes包围,double-quotes执行环境变量替换。 string中的任何单引号与变量替换无关。
你可以轻松测试它。在shell中做类似的事情
$ foo="bar"
$ echo "foo is '$foo'" # Will print foo is 'bar'
$ echo 'foo is "$foo"' # Will print foo is "$foo"