【问题标题】:Take input from user using cmd after running Python script在运行 Python 脚本后使用 cmd 从用户那里获取输入
【发布时间】:2020-05-29 18:42:26
【问题描述】:

我想在 Windows 中运行我的 py 脚本后接受用户的输入。

应该会弹出一个新的 cmd 并显示特定消息,例如“您希望继续 [y/n]”,并将此值存储在 py 脚本中的变量中,并且 cmd 应该在用户提供输入后自动关闭。 (使用 Python 3) 谁能帮忙。

【问题讨论】:

  • 您的意思是“x = input("您希望继续 [y/n]")”吗?还是要启动一个新的终端窗口?
  • 我想启动一个新的终端窗口(在 windows 中),它会在输入后自行关闭,主脚本将继续执行。

标签: python python-3.x subprocess popen python-os


【解决方案1】:

这是一种方法:

假设您有三个文件,第一个文件 (first_half.py) 是程序的前半部分,第二个文件 (ask.py) 是询问用户是否继续的地方,第三个文件 (second_half .py) 用于如果用户选择继续,它会被执行。

在你的 first_half.py python 文件中:

# Your code
import os
os.system('cmd /k "python ask.py"')

在 ask.py 中:

a = input("Do you wish to continue? ")
line = 5 # Choose which line of the second_half.py should define the variable
with open('second_half.py','r') as f:
    file = f.readlines()

if a == 'y':
    file.insert(line,'\na = "y"')
    with open('second_half.py','w') as f:
        f.write(''.join(file))
else:
    file.insert(line,'\na = "n"')
    with open('second_half.py','w') as f:
        f.write(''.join(file))

import os
os.system('second_half.py')

这可能不是您想要的,但确实适用于某些特定情况。

【讨论】:

  • 不幸的是,这对我不起作用。我有一个 while 循环,其中我正在检查一些要求,当未满足时,用户将收到一个提示,询问他们是否要继续。感谢您的努力
  • 对不起,我看看有没有其他办法。
【解决方案2】:

您可以使用 subprocess.run() 来做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2011-11-14
    • 2015-07-17
    • 2019-04-11
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多