Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --gui-script flag for running Python scripts with pythonw.exe on … #9152

Merged
merged 19 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions crates/uv-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2636,7 +2636,7 @@ pub struct RunArgs {
/// Run a Python module.
///
/// Equivalent to `python -m <module>`.
#[arg(short, long, conflicts_with = "script")]
#[arg(short, long, conflicts_with_all = ["script", "gui_script"])]
pub module: bool,

/// Only include the development dependency group.
Expand Down Expand Up @@ -2735,9 +2735,16 @@ pub struct RunArgs {
///
/// Using `--script` will attempt to parse the path as a PEP 723 script,
/// irrespective of its extension.
#[arg(long, short, conflicts_with = "module")]
#[arg(long, short, conflicts_with_all = ["module", "gui_script"])]
pub script: bool,

/// Run the given path as a Python GUI script.
///
/// Using `--gui-script` will attempt to parse the path as a PEP 723 script and run it with pythonw.exe,
/// irrespective of its extension. Only available on Windows.
#[arg(long, conflicts_with_all = ["script", "module"])]
pub gui_script: bool,

#[command(flatten)]
pub installer: ResolverInstallerArgs,

Expand Down
7 changes: 7 additions & 0 deletions crates/uv/src/commands/project/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1247,10 +1247,12 @@ impl std::fmt::Display for RunCommand {

impl RunCommand {
/// Determine the [`RunCommand`] for a given set of arguments.
#[allow(clippy::fn_params_excessive_bools)]
pub(crate) async fn from_args(
command: &ExternalCommand,
module: bool,
script: bool,
gui_script: bool,
connectivity: Connectivity,
native_tls: bool,
allow_insecure_host: &[TrustedHost],
Expand Down Expand Up @@ -1304,6 +1306,11 @@ impl RunCommand {
return Ok(Self::PythonModule(target.clone(), args.to_vec()));
} else if script {
return Ok(Self::PythonScript(target.clone().into(), args.to_vec()));
} else if gui_script {
if cfg!(windows) {
return Ok(Self::PythonGuiScript(target.clone().into(), args.to_vec()));
}
anyhow::bail!("`--gui-script` is only supported on Windows. Did you mean `--script`?");
}

let metadata = target_path.metadata();
Expand Down
2 changes: 2 additions & 0 deletions crates/uv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ async fn run(mut cli: Cli) -> Result<ExitStatus> {
command: Some(command),
module,
script,
gui_script,
..
}) = &mut **command
{
Expand All @@ -149,6 +150,7 @@ async fn run(mut cli: Cli) -> Result<ExitStatus> {
command,
*module,
*script,
*gui_script,
settings.connectivity,
settings.native_tls,
&settings.allow_insecure_host,
Expand Down
1 change: 1 addition & 0 deletions crates/uv/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ impl RunSettings {
only_dev,
no_editable,
script: _,
gui_script: _,
command: _,
with,
with_editable,
Expand Down
73 changes: 73 additions & 0 deletions crates/uv/tests/it/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2737,6 +2737,79 @@ fn run_script_explicit_directory() -> Result<()> {
Ok(())
}

#[test]
#[cfg(windows)]
fn run_gui_script_explicit() -> Result<()> {
let context = TestContext::new("3.12");

let test_script = context.temp_dir.child("script");
test_script.write_str(indoc! { r#"
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "PyQt5",
# ]
# ///
import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer

# Log environment info
print("Python executable:", sys.executable, file=sys.stderr)
print("Working directory:", os.getcwd(), file=sys.stderr)

try:
app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle("UV GUI Test")
window.setGeometry(100, 100, 200, 100)
window.show()

# Close after 1 second
QTimer.singleShot(1000, app.quit)
sys.exit(app.exec_())
except Exception as e:
print(f"Error initializing GUI: {e}", file=sys.stderr)
sys.exit(1)
"#})?;

let output = context.run().arg("--script").arg("script").output()?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be using --gui-script?

Copy link
Collaborator

@samypr100 samypr100 Nov 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, but would this pass with exit code 0 on a headless windows CI run?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you are right, and I'm slightly confused why/how we passed tests with that typo... Changing now and will see how it behaves!

if !output.status.success() {
eprintln!("GUI script failed with status: {}", output.status);
eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
}
assert!(output.status.success());

Ok(())
}

#[test]
#[cfg(not(windows))]
fn run_gui_script_not_supported() -> Result<()> {
let context = TestContext::new("3.12");
let test_script = context.temp_dir.child("script");
test_script.write_str(indoc! { r#"
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
print("Hello")
"#})?;

uv_snapshot!(context.filters(), context.run().arg("--gui-script").arg("script"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
error: `--gui-script` is only supported on Windows. Did you mean `--script`?
"###);

Ok(())
}

#[test]
fn run_remote_pep723_script() {
let context = TestContext::new("3.12").with_filtered_python_names();
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@ uv run [OPTIONS] [COMMAND]

<p>May be provided multiple times.</p>

</dd><dt><code>--gui-script</code></dt><dd><p>Run the given path as a Python GUI script.</p>

<p>Using <code>--gui-script</code> will attempt to parse the path as a PEP 723 script and run it with pythonw.exe, irrespective of its extension. Only available on Windows.</p>

</dd><dt><code>--help</code>, <code>-h</code></dt><dd><p>Display the concise help for this command</p>

</dd><dt><code>--index</code> <i>index</i></dt><dd><p>The URLs to use when resolving dependencies, in addition to the default index.</p>
Expand Down
Loading