如何在运行脚本时将布尔参数传递到子进程中



我正在使用子进程来运行脚本。其中一个脚本参数是布尔值。当我尝试传递此参数时,出现错误。

这是我的代码

scriptF = 'pythongScript.py'
arg1= 'arg1'
arg2= 'arg2'
arg3= True
subprocess.call(["python", scriptF, "--arg1", file1, "--arg2", file2, "--arg3", arg3])

这是我收到的错误消息

/usr/lib/python3.6/subprocess.py in call(timeout, *popenargs, **kwargs)
285     retcode = call(["ls", "-l"])
286     """
--> 287     with Popen(*popenargs, **kwargs) as p:
288         try:
289             return p.wait(timeout=timeout)
/usr/lib/python3.6/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors)
727                                 c2pread, c2pwrite,
728                                 errread, errwrite,
--> 729                                 restore_signals, start_new_session)
730         except:
731             # Cleanup if the child failed starting.
/usr/lib/python3.6/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
1293                             errread, errwrite,
1294                             errpipe_read, errpipe_write,
-> 1295                             restore_signals, start_new_session, preexec_fn)
1296                     self._child_created = True
1297                 finally:
TypeError: expected str, bytes or os.PathLike object, not bool

根据子进程文档:

所有调用都需要 args,并且应该是字符串或程序参数序列

所以一切都必须是字符串。单个字符串或字符串列表。因此,您可以执行以下操作:

scriptF = 'pythongScript.py'
arg1= 'arg1'
arg2= 'arg2'
arg3= True
subprocess.call([
"python", scriptF, 
"--arg1", file1,
"--arg2", file2,
"--arg3" if arg3 else ''
])

我假设在pythongScript.py你有一个看起来像这样的 argparse 参数

parser.add_argument('--arg3', action='store_true')

因此,如果--arg3不存在,那将是错误的

最新更新