【问题标题】:Unable to run process with arguments无法使用参数运行进程
【发布时间】:2019-09-23 03:52:46
【问题描述】:

程序逻辑

尝试使用带有 agrument 的 Process.Start() 运行 python 脚本。我正在尝试使用 GUI 自动化脚本,其中对于每个参数列表,都会生成并运行一个新的 python 命令。


问题

python 进程没有启动。 CMD 窗口显示很短的时间并关闭。基本上python脚本不会运行。

注意:通过cmd手动运行python脚本正常运行。此外,第二次尝试的代码(如下)在没有任何参数时运行,即仅在没有参数的情况下调用 python 脚本时。

因此,当我尝试传递参数并调用脚本时,某处出现错误。

尝试过的解决方案

代码:第一次尝试

For Each common_dir In common_dirs
     ' command for starting python script
     Dim command As String = utils.pyModDir & "Sys_File_Lister.py" & " " & "-d" & " " & "'" & common_dir & "'"
     Try
          'MsgBox(utils.python_Path)
          Process.Start(utils.python_Path, command).WaitForExit()
          Catch ex As Exception
               MsgBox(ex.Message.ToString)
     End Try
Next

代码:第二次尝试

Using proc As New Process()
     ' set the filename for process
     proc.StartInfo.FileName = utils.python_Path
     ' set the arguments for process
     proc.StartInfo.Arguments = """" & command & """"
     MsgBox(proc.StartInfo.Arguments.ToString)
     Try
          ' start the process
          proc.Start()
          ' wait for the process to complete
          proc.WaitForExit()
          ' if error
     Catch ex As Exception
          MsgBox(ex.Message.ToString)
End Using

代码:第三次尝试

这一次,我没有直接使用 python 调用 python 脚本,而是在 StartInfo.FileName 中调用了 cmd.exe,并在 StartInfo.Arguments 中调用了其他所有内容 按照建议。

这一次它导致文件未找到错误消息。

这是在 CMD 参数中传递的形成字符串:

从上面的命令中,也尝试从 python 路径中删除引号并将其保留为脚本路径,但同样的错误。

Using proc As New Process()
    ' set the filename for process
    proc.StartInfo.FileName = "cmd.exe /K "
    ' set the arguments for process
    proc.StartInfo.Arguments = """" & command & """"
    MsgBox(proc.StartInfo.Arguments.ToString)
    Try
        ' start the process
        proc.Start()
        ' wait for the process to complete
        proc.WaitForExit()
        ' if error
    Catch ex As Exception
        MsgBox(ex.Message.ToString)
    End Try
End Using

帮助:欢迎任何帮助!

【问题讨论】:

  • 尝试将字符串 cmd.exe 用于 ProcessStartInfo.FileName 属性,然后将所有内容放入 Arguments 属性中,但是以 /K 为所有内容添加前缀。这应该使控制台保持打开状态并显示任何错误消息
  • 感谢您的帮助,但这会导致错误(更新后的详细信息)。

标签: python vb.net process.start


【解决方案1】:

由于似乎只有在传递带有参数的 python 脚本时才会出现问题,所以一种快速的补救方法是将参数添加到文本文件中并在 python 脚本加载时读取它。..

它有效,但并没有解决当前的问题。但是,这是在我的情况下工作的次要解决方案。希望这可以帮助某人。以下是使用的python命令。我从 python 脚本中删除了参数解析器,而不是 -d arg 我从文件中读取参数,如下所示:

# check the list_from configuration
list_conf_path = "list_from.txt"
list_conf = ""
if isfile(list_conf_path):
    with open(list_conf_path, 'r') as f:
        list_conf = f.readline()
list_conf = list_conf.replace('"', '')
print(list_conf)

# start the main function
if list_conf != "":
    init(list_conf)
else:
    init("C:\\")

同样,不是精确的解决方案,而是次要的解决方案。

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多