子进程中带有变量的命令行

2022-01-23 00:00:00 python subprocess command variables

问题描述

我想在脚本的子进程中使用变量运行此命令.

I want to run this command with variables inside a subprocess in a script.

变量是:

filenames[k]

filenames 有很多名称(字符串),我可以使用 k 来处理.

filenames have many names (strings), which I can go through with k.

命令是:

python3 train.py "C:UsersTommydata\"+filenames[k] "C:UsersTommydata\"+filenames[k]+"_model" --choice A

我想在脚本中作为子进程运行这个命令:

I want to run this command inside a script as subprocess:

subprocess.run([" python3 train.py "C:UsersTommydata\"+filenames[k] "C:UsersTommydata\"+filenames[k]+"_model" --choice A "])

但是语法有问题.我不知道是什么.我在 Windows 上使用 Python 3.6.8 运行它.

But something is wrong with the syntax. I don't know what. I run this with Python 3.6.8 on Windows.


解决方案

我认为你迷失了字符串连接......你必须通过 run 或类似的方式执行 cmd:要么作为字符串或列表(因为列表通常更具可读性!)

I think you get lost with the string concatenation... you have to ways to execute a cmd with runor such: either as a string or as a list (as a list is usually more readable!)

案例:args as string

Case: args as string

cmd = f'python3 train.py "C:UsersTommydata\{filenames[k]}" "C:UsersTommydata\{filenames[k]}+_model" --choice A'

subprocess.run(args=cmd, shell=True)

案例:args as list

Case: args as list

cmd = f'python3 train.py "C:UsersTommydata\{filenames[k]}" "C:UsersTommydata\{filenames[k]}+_model" --choice A'

cmd = cmd.split(' ') # provided that no white spaces in the paths!!

subprocess.run(args=cmd, shell=False)

备注:

  • 新"非常好用.字符串连接 f"smt {variable} smt else" 其中 variable 是之前定义的变量

  • it is very handy the "new" string concatenation f"smt {variable} smt else" where variable is a variable defined before

如果你希望你的程序从 shell 启动,那么你需要添加一个 kwrags 参数 shell=True,默认 False.在这种情况下,根据您选择 args 是字符串还是列表,您应该更加小心:从文档中如果 shell 为 True,建议传递 `args作为一个字符串而不是一个序列"

if you want that your program will be launched from the shell then you need to add a kwrags parameter shell=True, default False. In this case, depending if you choose the args to be either a string or a list, you should be then more careful: from the docs "if shell is True, it is recommended to pass `args as a string rather than as a sequence"

查看 docs,位于 Popen Constructor,获取签名的完整描述

Have a look to the docs, at Popen Constructor, for a full description of the signature

相关文章