我正在学习Python,遇到了一些我不知道该怎么做的问题。为了简单起见,假设我有 2 个脚本:Main 和 CalledScript。我希望 Main 打开一个可执行文件并获取其 pid,将其分配给一个变量,然后将 CalledScript.py 作为子进程打开并将该变量作为参数传递给它。虽然我知道在大多数情况下使用导入将是更好的选择,但在我的情况下,由于项目的其他部分,我必须将其作为子进程运行。无论如何,当我这样做时,我总是收到错误。仅当我尝试发送 pid 时才会发生这种情况。如果我将下面的变量“thePid”分配给一些随机数,例如“555”,那么它就可以正常工作。 CalledScript 会接收它,将其打印到屏幕上,一切都很好。但尝试为其分配 cproc.pid 并发送它并不顺利。
话不多说,下面是一个简单的示例代码:
Main.py
from subprocess import Popen, PIPE
import sys
import subprocess
import os
cproc = Popen("C:\Test\Test.exe", stdin=PIPE, stdout=PIPE)
thePid = cproc.pid
theproc = subprocess.Popen(['C:\\CalledScript.py', thePid], shell=True)
CalledScript.py
import sys
print "thePid is: %r" % sys.argv[1]
我收到的错误:
Traceback (most recent call last):
File "main.py", line 12, in <module>
theproc = subprocess.Popen(['C:\\CalledScript.py
', cproc.pid], shell=True)
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 852, in _execute_child
args = list2cmdline(args)
File "C:\Python27\lib\subprocess.py", line 587, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: argument of type 'int' is not iterable
任何帮助都会非常出色!很抱歉这个可能非常明显的问题。我在谷歌上搜索了一下,但没有找到答案!前几天我刚刚开始摆弄 python,所以我还在学习!
最佳答案
尝试将 pid 作为字符串而不是 int 传递:
theproc = subprocess.Popen(['C:\\CalledScript.py', str(thePid)])
如果您将参数作为字符串列表传递,那么使用 shell=True
就没有意义。
关于python - 在 Windows 7 环境中将变量作为参数从 1 个 python 脚本传递到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10563883/