【问题标题】:Execute python file with variables使用变量执行python文件
【发布时间】:2017-07-29 22:16:00
【问题描述】:

我想将这两个变量传递给另一个 python 文件,我不想将它作为子进程启动。
我希望两个进程分开运行,因为 file1 有很多计算要做,不能等待 file2 的操作完成。

FILE1.PY

include os
name="one"
status="on"
os.system('F:\PythonSub\file2.py' name status)

FILE2.PY

include sys
name=sys.argv[0]
send=sys.argv[1]
print(send, name)

以上代码返回

send=sys.argv[1]
IndexError: list index out of range 

我做错了什么?

【问题讨论】:

标签: python multithreading operating-system


【解决方案1】:

使用subprocess 模块(该链接上的示例)。它支持异步启动进程(which os.system 不支持),并将参数作为参数传递。看起来你需要类似的东西:

subprocess.call(["F:\PythonSub\file2.py", name, status])

如果您想从进程中获取输出,您可能需要重定向stdin/stdout 流,shell 选项可能很有用。

编辑:这是错误的,因为subprocess.call 同步调用,而不是异步调用。您应该改用链接副本中描述的方法。

【讨论】:

  • 你应该使用subprocess.check_output而不是subprocess.call而不是重定向stdout流来获取输出
【解决方案2】:

试试这个

import os
name="one"
status="on"
os.system('F:\PythonSub\file2.py %s %s' % (name status))

【讨论】:

  • 包括 ?或者我错过了一个新功能
  • 应该是import
  • 啊只是复制粘贴OP!已编辑。谢谢
猜你喜欢
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
  • 2019-03-15
  • 1970-01-01
  • 2011-01-19
  • 2016-10-28
  • 1970-01-01
  • 2018-05-12
相关资源
最近更新 更多